在Dart中使用动态(可变)字符串作为正则表达式模式 [英] Use dynamic (variable) string as regex pattern in dart
问题描述
我正在尝试使用正则表达式
语言DART传递变量
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 ";
}`
谢谢
推荐答案
一个通用函数,用于将要放入正则表达式中的任何文字字符串作为文字模式部分,看起来像
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.
因此,如果您有 myfile.png
,则输出 escape('myfile。 png')
将是 myfile\.png
和。
仅匹配文字现在是点字符。
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.
您可以只使用
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!";
}
生成的正则表达式为 ^ \w {4,20} $
。
注意:
- 使用非原始字符串文字以使用字符串插值
- 在常规字符串文字中转义字符串锚的末尾以定义文字
$
char - 使用双反斜杠定义正则表达式转义序列(
\\d
以匹配数字等)
- 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.)
这篇关于在Dart中使用动态(可变)字符串作为正则表达式模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!