如何使用第一个逗号将字符串拆分为段落?
我有字符串: @address = "10 Madison Avenue, New York, NY - (212) 538-1884"
这样拆分它的最佳方法是什么?
10 Madison Avenue,
New York, NY - (212) 538-1884
String#split有第二个参数,结果数组中返回的最大字段数: http : //ruby-doc.org/core/classes/String.html#M001165
@address.split(",", 2)
将返回一个带有两个字符串的数组,在第一次出现“,”时拆分。
其余的只是使用插值构建字符串,或者如果你想让它更通用,例如Array#map
和#join
的组合
@address.split(",", 2).map {|split| "#{split}
" }.join("\n")
break_at = @address.index(",") + 1 result = "#{@address[0, break_at]}
#{@address[break_at..-1].strip}
"
而:
break_at = @address.index(", ") result = "#{@address[0, break_at+1]}
#{@address[break_at+1..-1]}
"
即使@address.split(",",2)
是正确的。 运行split
, partition
和regex
解决方案的基准测试,例如@adress.match(/^([^,]+),\s*(.+)/)
表明分区比split
好一点。
在2,6 GHz Intel Core 100_000
GB RAM计算机和100_000
运行: user system total real partition 0.690000 0.000000 0.690000 ( 0.697015) regex 1.910000 0.000000 1.910000 ( 1.908033) split 0.780000 0.010000 0.790000 ( 0.788240)