我有以下字符串:
'foo-bar'
'foo - bar'
'foo -bar'
'foo- bar'
'foo- bar-baz'
'foo - bar -baz'
'foo- bar baz'
等等。
在Ruby中,如何最好地使它们所有的连字符周围都没有空格?不带连字符的单词之间的空格应该保留。
预期结果示例: 'foo-bar' 'foo-bar-baz' 'foo-bar baz'
使用正则表达式是一种快速有效的方法:
"foo-bar -baz - blerp blorp".gsub(/\s*-\s*/, "-")
=> "foo-bar-baz-blerp blorp"
\s*
表示"零个或多个空白字符"。请注意,这将匹配制表符和空格。如果您只想匹配空格,请改用[ ]*
。/[ ]*/
而不是/ */
?如果您使用/x
,我会理解...可读性? - Amadan更通用的变体(不重复分隔符):
最初的回答"foo-bar -baz - blerp blorp".gsub(/\s*-\s*/) { |part| part.strip }
=> "foo-bar-baz-blerp blorp"
"foo-bar -baz - blerp blorp".gsub(/\s*-\s*/, &:strip)
- Aleksei Matiushkin使用正则表达式。我认为你的正则表达式应该等于这样:
使用正则表达式。我相信您的正则表达式应该类似于:
regex = /\s*-\s*/
test_strings = ["foo-bar baz", "foo - bar baz", "foo -bar"]
test_strings.map do |test_string|
test_string.gsub(regex, "-")
end
# => ["foo-bar baz", "foo-bar baz", "foo-bar"]
这里有一个很棒的应用程序可以帮助您构建正则表达式: https://rubular.com/
奖励提示,Original Answer翻译成"最初的回答"。
'-'
处拆分字符串,剥离子字符串并将它们重新连接起来。"foo - bar -baz".split('-').map(&:strip).join('-')
# => "foo-bar-baz"
\s*-\s*
而不是/\s*-\s*/
。import re
print(re.sub('\s*-\s*', '-', 'd - a co- ca ce -la ')) # "d-a co-ca ce-la "
虽然这个不起作用:
print(re.sub('/\s*-\s*/', '-', 'd - a co- ca ce -la ')) # "d - a co- ca ce -la "
str.gsub(/\s*-\s*/, '-')
的某种变体,但是假设str = "my - oh-\n my"
。那么str.gsub(/\s*-\s*/, '-') #=> "my-oh-my"
,这是不正确的。如果您希望删除连字符周围的空格,请删除空格而不是空白字符:str.gsub(/ *- */, '-') #=> "my-oh-\n my"
。 - Cary Swoveland