正则表达式在Dart中未返回任何匹配项,但可用于在线正则表达式测试器 [英] Regex returns no match in Dart but works in online regex testers
问题描述
我建立了一个正则表达式,它应该与有效的HTTP标头匹配。它可以在regexr上正常工作: https://regexr.com/4pnk9 ,正则表达式 ^([\w\-])+ :( ?! \s * $)。+ $
。我正在使用全局,多行和不区分大小写的标记(gim)。
I have built a regex which should match valid HTTP headers. It works, sort of, on regexr: https://regexr.com/4pnk9, with regex ^([\w\-])+:(?!\s*$).+$
. I am using the global, multi line and case insensitive flags (gim).
但是,当我在Flutter项目中实现它时,它什么都不匹配。除此之外,Dart还没有提供在RegExp中启用global的方法。
However when I implement it in my Flutter project, it does not match anything. Besides that Dart does not provide a way to enable global in RegExp.
谁能解释我为什么此regex在regexr.com上有效,但在我的Dart测试中却不能? / p>
Can anyone explain me why this regex works on regexr.com, but not in my Dart tests?
class Validators {
static final RegExp _headerFieldsRegExp = RegExp(
"^([\w\-])+:(?!\s*\$).+\$",
multiLine: true,
caseSensitive: false);
static bool headerFieldsValid(String headerFields) {
if (headerFields == null || headerFields.length == 0) {
return false;
}
String match = _headerFieldsRegExp.stringMatch(headerFields);
if (match == null) {
return false;
}
return headerFields.length == match.length;
}
}
void main() {
test('Test validating header fields', () {
String valid1 = 'Accept: json\nAuthorization: Bearer 12345';
expect(true, Validators.headerFieldsValid(valid1));
String valid2 = 'Accept: json\nAuthorization: Bearer 12345\n';
expect(true, Validators.headerFieldsValid(valid2));
String invalid1 = 'Accept: json\nAuthorization:\n';
expect(false, Validators.headerFieldsValid(invalid1));
String invalid2 = 'Accept: json\n\nAuthorization: Bearer 12345\n';
expect(false, Validators.headerFieldsValid(invalid2));
});
}
推荐答案
您可以要么使用
r"^([\w-])+:(?!\s*$).+$"
或
"^([\\w-])+:(?!\\s*\$).+\$"
请注意,在非原始字符串文字中,双反斜杠代表单个文字反斜杠。在原始字符串文字中,您不需要转义 $
符号,并且只需要一个反斜杠即可形成正则表达式转义。
Note that inside a non-raw string literal, the double backslashes stand for a single literal backslash. In a raw string literal, you do not need to escape the $
symbol and you only need a single backslash to form a regex escape.
这篇关于正则表达式在Dart中未返回任何匹配项,但可用于在线正则表达式测试器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!