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

ruby – 如何编写一个与任何顺序的字符匹配的正则表达式?

发布时间:2020-12-17 01:46:57 所属栏目:百科 来源:网络整理
导读:我正在尝试编写一个正则表达式,它将匹配一组字符而不考虑顺序.例如: str = "act" str.scan(/Insert expression here/) 会匹配: catacttcaatctaccta 但不会匹配ca,ac或cata. 我在StackOverflow上阅读了很多类似的问题和答案,但没有找到与我的目标完全匹配的
我正在尝试编写一个正则表达式,它将匹配一组字符而不考虑顺序.例如:

str = "act" 
str.scan(/Insert expression here/)

会匹配:

cat
act
tca
atc
tac
cta

但不会匹配ca,ac或cata.

我在StackOverflow上阅读了很多类似的问题和答案,但没有找到与我的目标完全匹配的问题.

为了澄清一点,我使用ruby并且不想允许重复字符.

解决方法

这是你的解决方案

^(?:([act])(?!.*1)){3}$

见它here on Regexr

^                  # matches the start of the string
    (?:            # open a non capturing group 
        ([act])    # The characters that are allowed and a capturing group
        (?!.*1)   # That character is matched only if it does not occur once more,Lookahead assertion
    ){3}           # Defines the amount of characters
$

唯一特别的想法是lookahead assertion,以确保不再重复的性格.

^和$是匹配字符串开头和结尾的锚点.

(编辑:李大同)

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

    推荐文章
      热点阅读