正则表达式反向引用不起作用
Regex backreference not working
我想匹配这个类似于 html 的模式:<12>Some content with \n in it<12>
重要的是,只有完整的项目才会被标记(数字必须匹配),这意味着当一个标签缺失时,内容不应被标记。 <12>Some content with \n in it<13>test<13>
这是我目前得到的:
(<\s*[0-9]+\>)(.*?[^<]*?)(<\s*[0-9]+\>)
这是我期望它应该起作用但实际上不起作用的结果:
(<\s*[0-9]+\>)(.*?[^<]*?)(<\s*[0-9]+\>)
我试过使用这个编辑器,但是反向引用没有像我预期的那样工作。为什么对第一个捕获组的反向引用不起作用?该解决方案应该适用于 C++。
试试这个:
<\s*(\d+)\s*>((.|\n)*?)<\s*\s*>
- 第一个捕获组 (\d+)
- \d+ 匹配一个数字(等于[0-9])
- +Quantifier — 匹配一次和无限次(贪心)
- (.|\n)*? .匹配任何字符(行终止符除外),并且 \n
匹配行终止符
- ?让它变得懒惰(懒惰)
- \1 对第一个捕获组的反向引用
C++14 代码示例:
#include <regex>
#include <string>
#include <iostream>
using namespace std;
int main()
{
string regx = R"(<\s*(\d+)\s*>((.|\n)*?)<\s*\s*>)";
string input = "<1>test1<1><2>Tes\nt2<2>sfsaf<3><4>test4<4>";
smatch matches;
while (regex_search(input, matches, regex(regx)))
{
cout<<matches[2]<<endl;
input = matches.suffix().str();
}
return 0;
}
我想匹配这个类似于 html 的模式:<12>Some content with \n in it<12>
重要的是,只有完整的项目才会被标记(数字必须匹配),这意味着当一个标签缺失时,内容不应被标记。 <12>Some content with \n in it<13>test<13>
这是我目前得到的:
(<\s*[0-9]+\>)(.*?[^<]*?)(<\s*[0-9]+\>)
这是我期望它应该起作用但实际上不起作用的结果:
(<\s*[0-9]+\>)(.*?[^<]*?)(<\s*[0-9]+\>)
我试过使用这个编辑器,但是反向引用没有像我预期的那样工作。为什么对第一个捕获组的反向引用不起作用?该解决方案应该适用于 C++。
试试这个:
<\s*(\d+)\s*>((.|\n)*?)<\s*\s*>
- 第一个捕获组 (\d+)
- \d+ 匹配一个数字(等于[0-9])
- +Quantifier — 匹配一次和无限次(贪心)
- (.|\n)*? .匹配任何字符(行终止符除外),并且 \n 匹配行终止符
- ?让它变得懒惰(懒惰)
- \1 对第一个捕获组的反向引用
C++14 代码示例:
#include <regex>
#include <string>
#include <iostream>
using namespace std;
int main()
{
string regx = R"(<\s*(\d+)\s*>((.|\n)*?)<\s*\s*>)";
string input = "<1>test1<1><2>Tes\nt2<2>sfsaf<3><4>test4<4>";
smatch matches;
while (regex_search(input, matches, regex(regx)))
{
cout<<matches[2]<<endl;
input = matches.suffix().str();
}
return 0;
}