gpt4 book ai didi

没有等号的 C++ Regex Alpha

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

我是 Regex 和 C++ 的新手。我的问题是,当我搜索 [a-zA-Z] 时,'=' 匹配。但这只是没有 '=' 的 a-z?

谁能帮帮我?

 string string1 = "s=s;";
enum states state = s1;

regex statement("[a-zA-Z]+[=][a-zA-Z0-9]+[;]");
regex rg_left_letter("[a-zA-Z]");
regex rg_equal("[=]");
regex rg_right_letter("[a-zA-Z0-9]");
regex rg_semicolon("[;]");

for (const auto &s : string1) {
cout << "Current Value: " << s << endl;
// step(&state, s);
if (regex_search(&s, rg_left_letter)) {
cout << "matching: " << s << endl;
} else {
cout << "not matching: " << s << endl;
}

// cout << "Step Executed with sate: " << state << endl;
}

这个输出:

Current Value: s
matching: s
Current Value: =
matching: =
Current Value: s
matching: s
Current Value: ;
not matching: ;

最佳答案

当你写作时

regex_search(&s, rg_left_letter)

您基本上是在 C 字符串 &s 中搜索字符匹配,从字符 s 开始。因此,您的循环将在剩余的子字符串中搜索匹配项

s=s;
=s;
s;
;

这将始终成功,除了最后一种情况,因为整个字符串中总是有一个字符适合您的正则表达式。但是请注意,这假设 std::string 添加了一些 0 终止,据我所知,如果您不明确使用 c_str() 方法,使您的代码成为 UB。您真正想要使用的是函数 regex_match,连同您的原始正则表达式一样简单:

#include <iostream>
#include <regex>

int main()
{
std::regex statement("[a-zA-Z]+[=][a-zA-Z0-9]+[;]");
if(std::regex_match("s=s;", statement)) { std::cout << "Hooray!\n"; }
}

关于没有等号的 C++ Regex Alpha,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47411475/

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