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

Diggory diggsey at googlemail.com
Wed May 29 20:32:49 PDT 2013


On Wednesday, 29 May 2013 at 23:33:30 UTC, timotheecour wrote:
> 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);
> }

That would be good (although you missed a few :P)

Technically any working "escapeRegex" would also function as a 
valid "escapeRegexReplace", although it might be slightly faster 
to have a specialised one.


More information about the Digitalmars-d-learn mailing list