我想在下面的字符串中找到0123的所有排列 01210210021212333212300213231102023103130001332121230221000012333333021032112
我可以使用正则表达式来为我提供字符串中0123匹配的排列吗? 如果有任何重叠的图案我也需要
“0123”在这里,我希望匹配[1023] [1230] [2301] [3012]
答案 0 :(得分:5)
不是正则表达式,而是C ++ 11:
#include <iostream>
#include <algorithm>
#include <string>
int main()
{
const std::string s("01210210021212333212300213231102023103130001332121230221000012333333021032112");
const std::string ref("0123");
if(ref.length() > s.length())
{
return 0;
}
for(int i = 0; i < s.length() - ref.length(); ++i)
{
if(std::is_permutation(s.cbegin()+i, s.cbegin()+i+ref.length(), ref.cbegin()))
{
const std::string extract(s, i, ref.length());
std::cout << extract << std::endl;
}
}
return 0;
}
例如使用g++ -std=c++11 -o sample sample.cpp
如果你绝对需要正则表达式:(?=[0123]{3})(.)(?!\1)(.)(?!\1|\2)(.)(?!\1|\2|\3).
这意味着:
(?=[0123]{3}) : positive assertion that the 4 next characters are 0, 1, 2, 3
(.) : capture first character
(?!\1) : assert that following character is not the first capture group
(.) : capture second character
(?!\1|\2) : assert that following character is neither the first nor the second capture group
etc.
答案 1 :(得分:0)
正则表达式无法满足您的要求。它无法从字符串生成排列。