我想解析像 (X->Y)
或 [X=>Y]
这样的字符串,并提取 X 和 Y 部分。我是这样做的:
// Example program
#include <iostream>
#include <string>
#include <regex>
int main()
{
std::string text1 = "(X->Y)";
std::string text2 = "[X=>Y]";
std::regex my_regex("\\(([A-Z]+)->([A-Z]+)\\)|\\[([A-Z]+)=>([A-Z]+)\\]");
std::smatch reg_match;
if(std::regex_match(text1, reg_match, my_regex)) {
std::cout << reg_match[1].str() << ' ' << reg_match[2].str() << std::endl;
} else {
std::cout << "Nothing" << std::endl;
}
}
它适用于 text1
,但它对 text2
给出空结果。我做错了什么?如果我用 text2 运行代码,为什么 reg_match[1]
和 reg_match[2]
中没有 X 和 Y?
最佳答案
这是因为当您匹配 text1
时,第 1 组和第 2 组会匹配:
\\(([A-Z]+)->([A-Z]+)\\)|\\[([A-Z]+)=>([A-Z]+)\\]
^^^^^^ ^^^^^
而在 text2
中,第 3 组和第 4 组匹配:
\\(([A-Z]+)->([A-Z]+)\\)|\\[([A-Z]+)=>([A-Z]+)\\]
^^^^^^ ^^^^^
所以对于 text2
,你必须使用 reg_match[3]
和 reg_match[4]
。
当然,更通用的解决方案是先检查 reg_match[1]
是否为空。如果是,则使用第 1 组和第 2 组,否则使用第 3 组和第 4 组。
关于c++ - 如何匹配环境不同的两个群体? C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57187750/