regex with literal (ie automatically replace '(' with '\(', etc) )

timotheecour timothee.cour2 at gmail.com
Wed May 29 16:33:29 PDT 2013


something like this, which we should have in std.regex:

string escapeRegex(string a){
	import std.string;
	enum transTable = ['[' : `\[`, '|' : `\|`, '*': `\*`, '+': `\+`, 
'?': `\?`, '(': `\(`, ')': `\)`];
	return translate(a, transTable);
}
string escapeRegexReplace(string a){
	import std.string;
//	enum transTable = ['$' : `$$`, '\\' : `\\`];
	enum transTable = ['$' : `$$`];
	return translate(a, transTable);
}

unittest{
	string a=`asdf(def[ghi]+*|)`;
	assert(match(a,regex(escapeRegex(a))).hit==a);
	string b=`$aa\/$ $$#@$\0$1#$@%#@%=+_`;
	auto s=replace(a,regex(escapeRegex(a)),escapeRegexReplace(b));
	assert(s==b);
}



On Wednesday, 29 May 2013 at 23:28:19 UTC, Timothee Cour wrote:
> See below:
>
> import std.stdio;
> import std.regex;
>
> void main(){
> "h(i".replace!(a=>a.hit~a.hit)(regex(`h\(`,"g")).writeln; 
> //this works, but
> I need to specify the escape manually
> // "h(i".replace!(a=>a.hit~a.hit)(regex(`h(`,"gl")).writeln;  
> //I'd like
> this to work with a flag, say 'l' (lowercase L) as in 
> 'litteral'.
> }
>
> note, std.array.replace doesn't work because I want to be able 
> to use
> std.regex' replace with delegate functionality as above.
> This is especially useful when the regex's first argument is 
> given as an
> input argument (ie is unknown), and we want to properly escape 
> it.
>
> Alternatively, (and perhaps more generally), could we have a 
> function:
> string toRegexLiteral(string){
> //replace all regex special characters (like '(' ) with their 
> escaped
> equivalent
> }



More information about the Digitalmars-d-learn mailing list