输入:
f = ["happy days",
"happy\ndays",
"happy,days",
"happy, days"]
patt = /some_regex/
在f
patt
上分割每个字符串后,我想要的输出是[“happy”,“days”]。
非常感谢!
答案 0 :(得分:12)
答案 1 :(得分:5)
答案 2 :(得分:3)
试试这个:
f.map{ |s| s.split /[,\s]+/}
=> [["happy", "days"], ["happy", "days"], ["happy", "days"], ["happy", "days"]]
答案 3 :(得分:1)
循环遍历数组,使用String#scan查找单词:
f = [
"happy days",
"happy\ndays",
"happy,days",
"happy, days"
]
require 'pp'
pp f.map{ |s| s.scan(/\w+/) }
>> [["happy", "days"], ["happy", "days"], ["happy", "days"], ["happy", "days"]]
答案 4 :(得分:0)
irb(main):242:0> "a\nb".split(/\n/)
[
[0] "a",
[1] "b"
]
答案 5 :(得分:0)
如果您需要拆分“逗号空格”或“换行符”,请尝试使用
“你的字符串”.replace(/ ^ \ s + $ / mg,'\ n')。replace(/(,\ s)| \ n + / gm, '〜')。分裂( '〜')
基本上这个特殊的正则表达式会有所帮助
/(,\ S)| \ N + /克