gpt4 book ai didi

ruby - 正则表达式 : if three letters are included

转载 作者:数据小太阳 更新时间:2023-10-29 08:54:39 26 4
gpt4 key购买 nike

我有几个词:hello, poison, world, search, echo ...我有一些字母 e, h, o现在我需要找到包含这些字母的所有单词。像 search, echo for e, h, o

我可以这样搜索:

words = %w[hello poison world search echo]
matched = words.select do |w|
%w[e,h,o].all?{ |l| w =~ /#{l}/ }
end

问题是如果字母是 o, o, ol, b, l 这个搜索将返回 true 像 openboil,但我需要搜索包含三个 o 或两个 l 和一个 b

更新:

leters = "abc"
words.select{ |w| w.count(letters) >= 3 }

更新 2

错误的解决方案,示例:

"lllllll".count("lua") #=> 5

最佳答案

您确定要正则表达式吗?字符串支持计算其中的值,您可以使用该功能。像这样:

words = ["pool", "tool", "troll", "lot"]
letters = "olo"

#find how many of each letter we need
counts = {}
letters.each { |v| counts[v] = letters.count(v) }

#See if a given work matches all the counts
# accumulated above
res = words.select do |w|
counts.keys.inject(true) do |match, letter|
match && (w.count(letter) == counts[letter])
end
end

关于ruby - 正则表达式 : if three letters are included,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4490183/

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