加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

正则表达式没有来自有限字符池的重复字符

发布时间:2020-12-14 06:03:22 所属栏目:百科 来源:网络整理
导读:有没有办法编写正则表达式来匹配只包含某些字符的字符串,并且永远不会重复这些字符?我已经使用set来编写一些代码来实现它,但是想知道是否有正则表达式来实现它. 例如,如果我只想要一个包含[A,B,C]的字符串,并且我希望匹配一个永远不会复制任何字符的字符串,
有没有办法编写正则表达式来匹配只包含某些字符的字符串,并且永远不会重复这些字符?我已经使用set来编写一些代码来实现它,但是想知道是否有正则表达式来实现它.

例如,如果我只想要一个包含[A,B,C]的字符串,并且我希望匹配一个永远不会复制任何字符的字符串,例如A,C,AB,AC,BC,ABC等,但从不匹配AA,BB,CC等

谢谢!

解决方法

使用 negative lookahead assertion很容易做到:

^(?!.*(.).*1)[ABC]+$

完全符合您的描述.

测试它live on regex101.com.

说明:

^      # Start of the string
(?!    # Assert that it's impossible to match...
 .*    # Any number of characters (including zero)
 (.)   # followed by one character (remember this one in group 1)
 .*    # that's followed by any number of characters
 1    # and the same character as before
)      # End of lookahead
[ABC]+ # Match one or more characters from this list
$     # until the end of the string

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读