Use dynamic (variable) string as regex pattern in dart

自古美人都是妖i 提交于 2021-01-27 10:18:52

问题


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


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



回答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'}$');


来源:https://stackoverflow.com/questions/50370676/use-dynamic-variable-string-as-regex-pattern-in-dart

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!