我试图在 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 上使用带有 -std=c++11 -stdlib=libc++ 标志的 clang++ 7.0.2。
我还尝试了带有 -std=c++11 -std=gnu++11 标志的 g++ 5.3.0。
最佳答案
你有两个问题:
- 你需要escape
\
.正则表达式(.)\1{3}
是正确的,但为了将其存储在字符串文字中,您需要将其转义为"(.)\\1{3 }”
。 - 你可能需要
std::regex_search
而不是std::regex_match
.字符串"KQQQQ"
与正则表达式(.)\1{3}
不匹配,但子字符串"QQQQ"
匹配。<
以下程序:
#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";
}
match = 0
search = 1
关于c++ - 带有反向引用的正则表达式在 C++ 中不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35836707/