I have a regex expression that I'm trying to create dynamically.
RegExp reg4 = RegExp(r'(two \s\w \s one)');
My intention is to replace the value at two to be set dynamically
I've tried this
var two = "two";
RegExp reg4 = RegExp(r'(' two ' \s\w \s one)');
But it doesn't work.
CodePudding user response:
You forgot the r
on the second part of the string:
var two = "two";
RegExp reg4 = RegExp(r'(' two r' \s\w \s one)');
// ^ <- that one!
Without that r
, the \s
s and \w
in the second string are interpreted as string escapes, and disappear before they get to the RegExp
parser.
I'll also point out that the result of (two \s\w \s one)
has a
applying to only the o
of two
.
You might want to create ((?:two) \s\w \s one)
instead, so you repeat the entire "two" string.
Another thing to consider is whether you want to match the two
variable's string verbatim, or if it can contain a RegExp too.
If you want it verbatim, so that a value of var two = "[NOTE]";
won't match a single character, the string should be escaped:
RegExp reg4 = RegExp(r'((?:' RegExp.escape(two) r') \s\w\s one)');
CodePudding user response:
Try this:
escape(String s) {
return s.replaceAllMapped(RegExp(r'[.* ?^${}()|[\]\\]'), (x) {return "\\${x[0]}";});
}