具有特定条件的正则表达式

时间:2016-12-01 12:22:22

标签: c++ regex

假设我想创建一个正则表达式来搜索字符串中的两个单词,但条件是它只匹配它们,如果我正在寻找的两个单词之间没有其中一个单词。例如:

string input {"Somebody has typed in some words here."}

我正在寻找某些单词和单词,但我只希望正则表达式匹配这些,如果它们之间没有键入的单词(键入的只是我不想要的几个单词中的一个)站在某人和话语之间)。哪个正则表达式实现了这一点?我已经尝试了几种方法,但它们都没有像我预期的那样工作。有人可以帮帮我吗?

2 个答案:

答案 0 :(得分:2)

我是通过避免使用regex来实现的,因为一旦你引入了regexNow you have 2 problems

假设:

  1. 搜索范围的开头:const auto first = "Somebody"s
  2. 搜索范围的结尾:const auto second = "words"s
  3. 范围内不应存在的字词集合:const vector<string> words = { "in"s }
  4. 输入字符串:const auto input = "Somebody has typed in some words here."s
  5. 我们可以这样做:

    const auto start = input.find(first) + size(first);
    const auto finish = input.find(second, start);
    
    if (start != string::npos && finish != string::npos) {
        istringstream range(input.substr(start, finish - start));
    
        if (none_of(istream_iterator<string>(range), istream_iterator<string>(), [&](const auto& i) { return find(cbegin(words), cend(words), i) != cend(words); })) {
            cout << "match\n";
        } else {
            cout << "not a match\n";
        }
    } else {
        cout << "not a match\n";
    }
    

    Live Example

    如果您与regex结婚,有一种方法可以使用regex执行此操作。例如,如果words包含:&#34; in&#34;,&#34; lorem&#34;,&#34; ipsum&#34;你想要的东西是:

    \bSomebody\b(?:(\bin\b|\blorem\b|\bipsum\b).*|.)*?\bwords\b

    然后我们只需要测试我们的匹配是否包含任何内容:

    const regex re("\\b" + first + accumulate(next(cbegin(words)), cend(words), "\\b(?:(\\b" + words.front(), [](const auto& lhs, const auto& rhs) { return lhs + "\\b|\\b" + rhs; }) + "\\b).*|.)*?\\b" + second + "\\b");
    smatch sm;
    
    if (regex_search(input, sm, re) && sm[1].length() == 0U) {
        cout << "match\n";
    } else {
        cout << "not a match\n";
    }
    

    Live Example

答案 1 :(得分:0)

试试这个正则表达式:(somebody)(?!.*(?:typed|nice)).*(words)。它匹配第一个单词后跟任意数量的空格和第二个单词。如果跟随任意数量的字符和特定单词,匹配将在某人之后停止。第1组匹配某人,第2组匹配单词。

相关问题