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
相关文章:
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 为什么在保护模式下继承升级不起作用
- 如何在全屏模式下(在OpenGL中)使背景透明
- 为什么使用__LINE_的代码在发布模式下在MSVC下编译,而不是在调试模式下
- 派生类是否可以在抽象工厂设计模式中具有数据成员
- 此模式的C++RegEx
- avrogencpp能为模式中的每种类型生成单独的头文件吗
- 使用可变模板的Broadcaster/Listener模式
- c++方法参数只能在linux的发布模式下自行更改
- 资源管理设计模式
- 使用 mod_gsoap 部署服务时,如何在 Gsoap 中更改 soap 上下文的模式?
- C++ 无法在字符数组中使用 for 循环打印字母模式
- 小字符串优化(调试与发布模式)
- 可视化C++:发布模式的运行时库作为'Multi-threaded Debug DLL'
- 如何设计具有不同类型的通知和观察器的观察者模式?
- 在C++的一系列数字中查找重复模式
- 是否允许使用带有"w+"模式的 freopen 进行标准设置?
- C++ 使用存储在动态数组中的文本文件中的数据查找模式
- С++ wxWidgets:代码架构,设计原则和模式
- 以只读模式打开数据库时SQLITE_CANTOPEN错误