["1234-6ren">
gpt4 book ai didi

ruby - 从字符串中删除字符串模式和符号

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

我需要从短语 "not" 和主题标签 (#) 中清理一个字符串。 (我还必须去掉空格和大写锁定并以数组形式返回它们,但我处理了后三个。)

期望:

"not12345"       #=> ["12345"]
" notabc " #=> ["abc"]
"notone, nottwo" #=> ["one", "two"]
"notCAPSLOCK" #=> ["capslock"]
"##doublehash" #=> ["doublehash"]
"h#a#s#h" #=> ["hash"]
"#notswaggerest" #=> ["swaggerest"]

这是我的代码

def some_method(string)
string.split(", ").map{|n| n.sub(/(not)/,"").downcase.strip}
end

除了散列测试之外,以上所有测试都完成了我需要做的事情。我不知道如何摆脱哈希;我尝试修改正则表达式部分:n.sub(/(#not)/), n.sub(/#(not)/), n .sub(/[#]*(not)/) 无济于事。如何使正则表达式删除 #

最佳答案

arr = ["not12345", "   notabc", "notone, nottwo", "notCAPSLOCK",
"##doublehash:", "h#a#s#h", "#notswaggerest"].

arr.flat_map { |str| str.downcase.split(',').map { |s| s.gsub(/#|not|\s+/,"") } }
#=> ["12345", "abc", "one", "two", "capslock", "doublehash:", "hash", "swaggerest"]

当 block 变量str设置为"notone, nottwo"时,

s = str.downcase
#=> "notone, nottwo"
a = s.split(',')
#=> ["notone", " nottwo"]
b = a.map { |s| s.gsub(/#|not|\s+/,"") }
#=> ["one", "two"]

因为我用了Enumerable#flat_map , "one""two" 被添加到返回的数组中。当 str #=> "notCAPSLOCK",

s = str.downcase
#=> "notcapslock"
a = s.split(',')
#=> ["notcapslock"]
b = a.map { |s| s.gsub(/#|not|\s+/,"") }
#=> ["capslock"]

关于ruby - 从字符串中删除字符串模式和符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39129297/

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