繁体   English   中英

正则表达式匹配排列序列

[英]Regex to match sequence of permutations

给定一组 n 个字符,我们需要什么正则表达式来匹配这些字符的 0-x 排列序列?

我们想要排列。 给定 3 个字符 A、B、C 的集合,我们要匹配 ABC、ACB、BAC、BCA、CAB、CBA。

然而,我们想要匹配这些排列的序列。 序列可能包含 0 个或多个排列,这意味着我们要匹配空字符串,ABC、ABCBCA、BACCAB、BCAABCCBAABC 等。

我能够找到匹配排列的解决方案,但无法修改它以匹配一系列排列

我知道有时使用的正则表达式引擎可能会有所作为。 我想在 C# 的Microsoft.VisualStudio.TestTools.UnitTesting.StringAssert.Matches方法中使用这个正则表达式,这应该有所不同。 我们只是想检查测试方法的输出字符串是否与此正则表达式匹配,即是给定字符集的排列序列。

我不能太推荐1在这里使用正则表达式!

n = 3且字符为'A''B''C'时,您可以使用以下正则表达式来测试字符串的一致性:

/^(?:([ABC])(?!\1)([ABC])(?!\1|\2)[ABC])*$/

演示

正则表达式可以通过以自由间距模式编写来实现自文档化:

/
^           # match beginning of line
(?:         # begin non-capture group
  ([ABC])   # match 'A', 'B' or 'C' in capture group 1
  (?!\1)    # next character cannot be the content of capture group 1
  ([ABC])   # match 'A', 'B' or 'C' in capture group 2
  (?!\1|\2) # next character cannot be the content of capture group 1 or 2
  [ABC]     # match 'A', 'B' or 'C'
)           # end non-capture group
*           # execute non-capture group 0+ times
$           # match end of line
/x          # free-spacing mode

(?!\\1|\\2)是一个负面的前瞻

我使用了行首和行尾锚点来促进链接的测试,但字符串开头和结尾的锚点会更合适( \\A\\z )。

1 意在字面解释。

我猜你可以用一个小帮手

static bool Check(string source, string target)
{
   int? sLen = source?.Length, tLen = target?.Length;

   if (!(sLen > 0) || !(tLen > 0) || tLen % sLen != 0)
      return false;

   IEnumerable<string> Chunks(string str, int chunkSize)
      => Enumerable.Range(0, str.Length / chunkSize)
                   .Select(i => str.Substring(i * chunkSize, chunkSize));

   return Chunks(target, source.Length).All(x => source.All(x.Contains));

}

这可能比正则表达式快很多,并且可以处理空值

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM