RegExp匹配由一组有限字符组成的字符串,而不重用任何字符 [英] RegExp to match string formed with a limited set of characters without reusing any character

查看:177
本文介绍了RegExp匹配由一组有限字符组成的字符串,而不重用任何字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有很多这样的人物: ABBCD

I have a bunch of characters like this: A B B C D

我有几个像这样的空格: _ _ _

And I have a few spaces like this: _ _ _

有没有办法使用正则表达式匹配任何可以通过将可用字符拖动到空白空间而形成的字符串?

Is there a way to use regular expression to match any string that can be formed by "dragging" the available characters into the empty spaces?

所以在这个例子中,这些是一些有效的匹配:

So in the example, these are some valid matches:

A B C
A B B
B C B
D A B

但这些无效:

A A B    // Only one 'A' is available in the set
B B B    // Only two 'B's are available in the set

很抱歉,如果之前已经询问过。

Sorry if it has already been asked before.

推荐答案

vks的解决方案可以正常运行,这里通过添加到符合_ _ _规则:

vks's solution would work properly, and here's it optimised with additions to fulfill the "_ _ _" rule:

^(?!(?:[^A]*A){2})(?!(?:[^B]*B){3})(?!(?:[^C]*C){2})(?!(?:[^D]*D){2})(?:[ABCD](?:\s|$)){3}

这是一个正则表达式演示

原始版本的变化正则表达式:


  • 由于我们使用的是Java,因此删除捕获组 - Java正则表达式实现在匹配期间花费时间编写捕获的组)。

  • 为了正则表达式的可读性,锚点 ^ 被移到前面。

  • Capturing groups are removed since we're in Java - Java regex implementation dedicates time to write captured groups during matching).
  • The anchor ^ is moved in front for readability of the regex.

正则表达式解释:


  • ^ 在比赛开始时断言位置。

  • (?!否定前瞻 - 断言我们的位置匹配以下内容,而不移动指针:

  •     (?:[^ A] * A){2} 两个A s(文字字符),非 以最佳方式滚动。

  • 关闭群组。

  • (?!( ?:[^ B] * B){3})与上述组相同 - 断言B s在比赛中。

  • (?!(?:[^ C] * C){2})断言<在比赛中强>不两个C

  • (?!(?:[^ D] * D){2})断言比赛中有两个D

  • (?:非捕获组:匹配以下内容而不捕获。

  •    [ABCD] 列表中的任何字符ABC,或者D

  •    (?:\ s | $)空格,或字符串的结尾。

  • ){3} 三次 - 必须完全匹配序列三次才能实现_ _ _规则。

  • ^ Asserts position at the start of the match.
  • (?! Negative lookahead - Asserts that our position does not match the following, without moving the pointer:
  •     (?:[^A]*A){2} Two "A"s (literal character), with non-"A"s rolled over in an optimal way.
  • ) Closes the group.
  • (?!(?:[^B]*B){3}) Same as the above group - Asserts that there are not three "B"s in the match.
  • (?!(?:[^C]*C){2}) Asserts that there are not two "C"s in the match.
  • (?!(?:[^D]*D){2}) Asserts that there are not two "D"s in the match.
  • (?: Non-capturing group: Matches the following without capturing.
  •     [ABCD] Any character from the list "A", "B", "C", or "D".
  •     (?:\s|$) A whitespace, or the end of string.
  • ){3} Three times - Must match the sequence exactly three times to fulfill the "_ _ _" rule.

使用正则表达式:

boolean fulfillsRule(String str) {
    Pattern tripleRule = Pattern.compile("^(?!(?:[^A]*A){2})(?!(?:[^B]*B){3})(?!(?:[^C]*C){2})(?!(?:[^D]*D){2})(?:[ABCD](?:\s|$)){3}");
    return tripleRule.matcher(str).find();
}

这篇关于RegExp匹配由一组有限字符组成的字符串,而不重用任何字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆