gpt4 book ai didi

ruby - 如何编写一个可以按任意顺序匹配字符的正则表达式?

转载 作者:数据小太阳 更新时间:2023-10-29 07:22:36 24 4
gpt4 key购买 nike

我正在尝试编写一个正则表达式来匹配一组字符而不考虑顺序。例如:

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

会匹配:

cat
act
tca
atc
tac
cta

但不会匹配 caaccata

我在 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 , 以确保字符不重复。

^$ 是匹配字符串开头和结尾的 anchor 。

关于ruby - 如何编写一个可以按任意顺序匹配字符的正则表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14513595/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com