gpt4 book ai didi

ruby - 如何使用正则表达式从数组中进行选择?

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

我有一段代码要求用户输入 Cats 或 Dogs,然后它会在一个数组中搜索包含 Cats 或 Dogs 一词的所有内容,然后将它们全部排除。

print "Cats or Dogs? "
userinput = gets.chomp

lines = [["Cats are smarter than dogs"],["Dogs also like meat"], ["Cats are nice"]]

lines.each do |line|
if line =~ /(.*?)#{userinput}(.*)/
puts line
end
end

所以如果我要输入猫。我应该得到两句话:

Cats are smarter than dogs
Cats are nice

你甚至可以更智能地输入,我会得到

Cats are smarter than dogs

我正在严格寻找使用正则表达式搜索数组或字符串并取出与表达式匹配的行/句子的方法。

如果有人想知道,lines 数组最初来自一个文件,我将每一行都变成了一个数组部分。


编辑:

哇,我在编码世界走了多远。

print "Cats or Dogs? "
userinput = gets.chomp

lines = [["Cats are smarter than dogs"],["Dogs also like meat"], ["Cats are nice"]]

lines.each do |linesInside|
linesInside.each do |line|
if line =~ /(.*?)#{userinput}(.*)/
puts line
end
end
end

只花了 5 秒钟就解决了我当时花了很长时间才放弃的问题。

最佳答案

试试这个

...
lines = ["Cats are smarter than dogs", "Dogs also like meat", "Cats are nice"]
regexp = Regexp.new(userinput)
selected_lines = lines.grep(regexp)
puts selected_lines

这是如何工作的?

  • grep 使用模式匹配过滤数组
  • 请注意,我正在使用一个字符串数组。您的示例代码使用了一个单元素数组,我假设您的意思是只使用一个字符串数组。

关于ruby - 如何使用正则表达式从数组中进行选择?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41517528/

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