1

我想在 01210210021212333212300213231102023103130001332121230221000012333333021032112 下面的字符串中找到 0123 的所有排列

我可以有一个正则表达式,可以给我字符串中 0123 匹配的排列吗?我还需要是否有任何重叠的图案

“0123”在这里我想要匹配 [1023][1230][2301][3012]

4

2 回答 2

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.
于 2013-07-18T11:35:08.530 回答
0

正则表达式无法满足您的要求。它不能从字符串生成排列。

于 2013-07-18T11:29:25.740 回答