Use dynamic (variable) string as regex pattern in dart

4,879

Solution 1

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.)

Solution 2

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'}$');
Share:
4,879
user5084949
Author by

user5084949

Updated on December 05, 2022

Comments

  • user5084949
    user5084949 over 1 year

    i am trying to pass variable in regex language DART

      `betweenLenth(val, field, [min = 4, max = 20]) {
         final RegExp nameExp = new RegExp(r'^\w{" + min + "," + max + "}$');
         if (!nameExp.hasMatch(val))
         return field + " must be between $min - $max characters ";
       }`
    

    thanks

  • User Rebo
    User Rebo almost 2 years
    How to handle matching brakets ([0-9]|efg)? Thx :D