在以下情况下,我希望QRegularExpressionMatch返回true:
所以,我做了
QRegularExpression rx("(^(\\bFO\\s\\b|\\@\\bFOOB\\b)) | (\\bFOOBAR\\b)");
QString string0 = "Anywhere FOOBAR in the string";
QString string1 = "FO in the beginning";
QString string2 = "@FOOB in the beginning";
QRegularExpressionMatch match = rx.match(string1);
if (match.hasMatch())
QTextStream(stdout) << match.captured(0) << endl;在上面的代码中,有三种模式。FO和@FOOB字符串开头的第一个和第二个匹配,第三个模式匹配字符串中的任何位置。
没有第三种模式,代码在string1和string2中工作得很好。对于第三种模式,它只适用于string0和string2,而不适用于string1。我猜FO后的空间不匹配第三种模式,那么所有的匹配都失败了?在第一、第二和第三种模式之间有一个“操作符”!
或者我错过了什么,有人能帮忙吗?谢谢!
编辑:在我发布30秒后,找到解决方案:这些额外空间是问题所在
QRegularExpression rx("(^(\\bFO\\s\\b|\\@\\bFOOB\\b)) | (\\bFOOBAR\\b)");
^ ^ 但我不相信!那我们为什么要用括号呢?
发布于 2017-12-06 16:34:49
简介
正如您已经提到的,正则表达式中有空格,这就是regex无法工作的原因。此解决方案减少了返回匹配所需的步骤数。
代码
如果您只想确保字符串是有效的,则可以使用下面的正则表达式。注意,如果\s是绝对必需的(并且在^FO选项之后一个单词边界\b是不够的,您可以简单地将它添加到下面的正则表达式中,这样FO就变成了FO\s )。
^(?:@FOOB|FO|.*\bFOOBAR)\b.*如果您正在寻找有效的字符串并尝试返回匹配,则可以使用以下正则表达式。
(?:^(?:@FOOB|FO)|\bFOOBAR)\b结果
输入
Anywhere FOOBAR in the string
FO in the beginning
@FOOB in the beginning
FOOBAR is in the string
In the string is FOOBAR
@FOOBAR is valid because foobar (uppercase) exists
Anywhere FOOBARY in the string
Anywhere FOOBA in the string
FOO is not a valid start
@FOOBA is not a valid start
The @FOOB is not at the start输出
以下仅显示匹配
Anywhere FOOBAR in the string
FO in the beginning
@FOOB in the beginning
FOOBAR is in the string
In the string is FOOBAR
@FOOBAR is valid because foobar (uppercase) exists解释
^在行开始处的断言位置(?:@FOOB|FO|.*\bFOOBAR)非捕获组以匹配下列之一@FOOB匹配这个字面意思FO匹配这个字面意思.*\bFOOBAR匹配以下.*任何字符任意次数\b将位置断言为单词边界FOOBAR匹配这个字面意思
\b将位置断言为单词边界.*匹配任意字符的次数。发布于 2017-12-06 16:36:31
在清除不必要的空间之后,您可以进一步修剪regex:
QRegularExpression rx("^(?:FO\\s|@FOOB\\b)|\\bFOOBAR\\b");详细信息:
^(?:FO\\s|@FOOB\\b) - FO和字符串开头的任何空格或整个单词@FOOB。| -或\\bFOOBAR\\b -一个完整的词FOOBARhttps://stackoverflow.com/questions/47678786
复制相似问题