qRegulareXpression匹配模式

QRegularExpression match pattern

本文关键字:模式 qRegulareXpression      更新时间:2023-10-16

我想 qregularexpressionmatch 在以下情况下返回true:

  • String 使用FO启动。" fo 之后有一个空间"
  • 字符串 with @foob。
  • 字符串包含 foobar。

所以,我做到了:

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。使用第三种模式,它仅适用于字符串0和String2,而不是为String1。我想FO之后的空间与第三个模式不匹配,然后所有比赛都失败了?有|[第一,第二]和第三种模式之间的操作员!
还是我想念一些东西,有人可以帮忙?谢谢!

编辑:我发布后30秒查找解决方案:这些额外空间是问题

QRegularExpression rx("(^(\bFO\s\b|\@\bFOOB\b)) | (\bFOOBAR\b)");  
                                                     ^ ^ 

,但我不相信!那为什么我们使用括号?

简介

正如您提到的,您的正则有空格,这就是为什么正则是不起作用的原因。该解决方案减少了返回匹配所需的步骤数。

代码

如果您只想确保字符串有效,则可以使用下面的正则表达式。请注意,如果s是绝对必需的(并且在^FO选项之后,单词边界b不够,则可以将其添加到下面的正则表达式中,以便FO成为FOs

请参阅此处使用的正则

^(?:@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断言作为单词边界的位置
  • .*匹配任何字符的任何次数

您可以在恢复不必要的空间后再修剪正则是:

QRegularExpression rx("^(?:FO\s|@FOOB\b)|\bFOOBAR\b");

详细信息:

  • ^(?:FO\s|@FOOB\b)- FO和字符串开始时的任何whitespace或一个整个单词 @FOOB
  • |-或
  • \bFOOBAR\b-一个整个单词FOOBAR