没有等号的C ++ Regex Alpha

时间:2017-11-21 11:02:05

标签: c++ regex

我是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: ;

2 个答案:

答案 0 :(得分:1)

写作时

regex_search(&s, rg_left_letter)

你基本上从字符s开始搜索C-String &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"; }
}

答案 1 :(得分:0)

这对我有用:

 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;
    }