[英]Split a string at every occurrence of particular character?
I would like to pass a sequence of characters into a function as a string and have it return to me that string split at the following characters: 我想将一个字符序列作为字符串传递给函数,并让我将字符串拆分为以下字符:
@ # $ % ^ & *
such that if the string is 这样,如果字符串是
'hey#man^you*are#awesome'
the program returns 程序返回
'hey man you are awesome' “嘿,你真棒”
How can I do this? 我怎样才能做到这一点?
To split the string you can use String#split
要分割字符串,可以使用
String#split
'hey#man^you*are#awesome'.split(/[@#$%^&*]/)
#=> ["hey", "man", "you", "are", "awesome"]
to bring it back together, you can use Array#join
将其重新组合在一起,可以使用
Array#join
'hey#man^you*are#awesome'.split(/[@#$%^&*]/).join(' ')
#=> "hey man you are awesome"
split
and join
should be self-explanatory. split
和join
应该是不言自明的。 The interesting part is the regular expression /[@#$%^&*]/
which matches any of the characters inside the character class [...]
. 有趣的部分是正则表达式
/[@#$%^&*]/
,它匹配字符类[...]
中的任何字符。 The above code is essentially equivalent to 上面的代码基本上等同于
'hey#man^you*are#awesome'.gsub(/[@#$%^&*]/, ' ')
#=> "hey man you are awesome"
where the gsub
means "globally substitute any occurence of @#$%^&* with a space". 其中
gsub
意思是“用gsub
将@#$%^&*的所有出现位置全局替换”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.