带有反向引用的正则表达式在C ++中不匹配

时间:2016-03-07 05:24:19

标签: c++ regex

我正在尝试在C ++中匹配4个相同的字符。

这些应匹配= KQQQQ, ZZZZQ

这是我到目前为止所尝试的:

std::string mano_to_reg = "KQQQQ";
std::regex pokar("(.)\1{3}");
std::smatch match;

std::cout << "match = " << std::regex_match(mano_to_reg, match, pokar) << "\n";

但它不会匹配。

我也尝试了std::regex_search,但它也不匹配。

我尝试过使用基本和扩展语法

我也尝试将我的模式更改为"(.)\1{4}""((.)\1{3})"以及其他所有组合。

我尝试将其他模式与其他字符串匹配,其中大多数都有效。似乎问题是反向引用,但我到处寻找,我找不到它为什么不匹配。

我在OS X 10.11.3上使用了clang ++ 7.0.2,其中-std = c ++ 11 -stdlib = libc ++ flags。

我也尝试过使用-std = c ++ 11 -std = gnu ++ 11标志的g ++ 5.3.0。

1 个答案:

答案 0 :(得分:2)

你有两个问题:

  1. 您需要escape \。正则表达式(.)\1{3}是正确的,但为了将其存储在字符串文字中,您需要将其转义为"(.)\\1{3}"
  2. 您可能需要std::regex_search而不是std::regex_match。字符串"KQQQQ"与正则表达式(.)\1{3}不匹配,但子字符串"QQQQ"不匹配。
  3. 以下计划:

    #include <iostream>
    #include <regex>
    #include <string>
    
    int main() {
        std::string mano_to_reg = "KQQQQ";
        std::regex pokar("(.)\\1{3}");
        std::smatch match;
    
        std::cout << "match  = " << std::regex_match(mano_to_reg, match, pokar) << "\n";
        std::cout << "search = " << std::regex_search(mano_to_reg, match, pokar) << "\n";
    }
    

    outputs:

    match  = 0
    search = 1