gpt4 book ai didi

javascript - 计算两个不同单词在一个字符串中出现的次数 - 可能只用一个正则表达式吗?

转载 作者:行者123 更新时间:2023-11-29 18:31:50 24 4
gpt4 key购买 nike

假设我们有一个像“catdogbirdbirdcat”这样的字符串。确定“cat”是否正好出现两次和“dog”是否正好出现一次的最佳方法是什么?

 (cat|dog)

我们可以将我们的字符串与这个正则表达式进行匹配,并得到一个数组并计算匹配的元素。或者我们可以做两个单独的正则表达式,一个用于猫,一个用于鸟,然后从那里开始。

有没有一种方法可以一次性使用一个正则表达式来做到这一点?

最佳答案

嗯,我不知道这是不是最好的方法,而且很丑。但是,这是一种方法:

/
^ #The start of the string.
(?= #A non-capturing lookaround.
#so that you can check both conditions.
(?: #A non-capturing group.
(?:(?!cat).)* #Capture text, that doesn't have cat included.
cat #Check for the text cat
(?:(?!cat).)* #See above.
){2} #Two of these
$ #The end of the string.
)
(?= #Then do the same for dog
(?:(?!dog).)*
dog
(?:(?!dog).)*
$
) #Only one dog though.
/x #The x flag just means ignore whitespace for readability.
#You can also do this though:

/^(?=(?:(?:(?!cat).)*cat(?:(?!cat).)*){2}$)(?=(?:(?!dog).)*dog(?:(?!dog).)*$)/

关于javascript - 计算两个不同单词在一个字符串中出现的次数 - 可能只用一个正则表达式吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7394581/

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