gpt4 book ai didi

c++ - regex_match 未按预期工作

转载 作者:行者123 更新时间:2023-11-28 00:50:00 25 4
gpt4 key购买 nike

这是我的代码:

#include <iostream>
#include <string.h>
#include <regex>

using namespace std;

int main () {

string test = "COPY" ;
regex r1 = regex ("(COPY\b)(.*)") ;
if (regex_match (test,r1) ) {
cout << "match !!" ;
} else {
cout << "not match !!";
}

好吧,我认为这段代码打印出“匹配!!” ,这就是我想要的。
但是,它给我一个“不匹配!!”
我该怎么办?

注意:
我希望匹配“COPY”,但不匹配“COPYs”或“COPYYY”,因此我在代码中使用了“\b”。

最佳答案

您需要对 \b 进行两次转义,因为 \ 字符是 C/C++ 中的“转义”序列,就像放置换行符时,您使用 \n 即使那是一个字符,而不是两个。因此,您的表达式从:"(COPY\b)(.*)" 变为:"(COPY\\b)(.*)"

对于极端情况,如果你想匹配正则表达式中的 \ 字符,你需要这样:"\\\\" 因为 \ 字符也是转义字符,因此您正在转义。

仅供引用,这就是为什么在 .NET 中他们经常将原始字符串语法用于正则表达式,然后您不需要转义它。其他一些语言没有此作为转义字符,因此正则表达式更容易。

关于c++ - regex_match 未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14663051/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com