C 正则alpha没有相等的符号

C++ Regex Alpha without Equal sign

本文关键字:符号 正则 alpha      更新时间:2023-10-16

我是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-string &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"; }
}

这对我有用:

 int main(void) {
        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) {
        for (int i = 0; i < string1.size(); i++) {
            cout << "Current Value: " << string1[i] << endl;
            // step(&state, s);
            if (regex_match(string1.substr(i, 1), rg_left_letter)) {
                cout << "matching: " << string1[i] << endl;
            } else {
                cout << "not matching: " << string1[i] << endl;
            }
            // cout << "Step Executed with sate: " << state << endl;
        }
        cout << endl;
        return 0;
    }