Use dynamic (variable) string as regex pattern in dart
A generic function to escape any literal string that you want to put inside a regex as a literal pattern part may look like
escape(String s) {
return s.replaceAllMapped(RegExp(r'[.*+?^${}()|[\]\\]'), (x) {return "\\${x[0]}";});
}
It is necessary because an unescaped special regex metacharacter either causes a regex compilation error (like mismatched (
or )
) or may make the pattern match something unexpected. See more details about escaping strings for regex at MDN.
So, if you have myfile.png
, the output of escape('myfile.png')
will be myfile\.png
and the .
will only match literal dot char now.
In the current scenario, you do not have to use this function because max and min thresholds are expressed with digits and digits are no special regex metacharacters.
You may just use
betweenLenth(val, field, [min = 4, max = 20]) {
final RegExp nameExp = new RegExp("^\\w{$min,$max}\$");
if (!nameExp.hasMatch(val))
return field + " must be between $min - $max characters ";
return "Correct!";
}
The resulting regex is ^\w{4,20}$
.
Note:
- Use non-raw string literals in order to use string interpolation
- Escape the end of string anchor in regular string literals to define a literal
$
char - Use double backslashes to define regex escape sequences (
"\\d"
to match digits, etc.)
You can't use string-interpolation with raw strings.
With interpolation
final RegExp nameExp = new RegExp('^\\w{"$min","$max"}\$');
final RegExp nameExp = new RegExp('^\\w{$min,$max}\$');
with concatenation
final RegExp nameExp = new RegExp(r'^\w{"' + min + '","' + max + r'"}$');
final RegExp nameExp = new RegExp(r'^\w{' + min + ',' + max + r'}$');