我有一系列字符串,包括一个或多个数字(在这种情况下的数字为123,123,123),格式如下
"This is a number 123,124,123"
"These are some more numbers 123,345,123; 231,123,123; 124,152,123"
"This one is an odd situation 123,124,125; 123,123,123; more text"
将这些数字解析为数组或字符串的最简洁方法是什么?我可以拆分它,看起来像这样?
"123,124,123"
"123,345,123;231,123,123;124,152,123"
"123,124,125;123,123,123;"
最终我希望能够将这样的数字分开。
"123,124,123"
"123,345,123" "231,123,123" "124,152,123"
"123,124,125" "123,123,123"
目前正在尝试使用
"string".scan( /\d/ )
但显然这只是给了我没有逗号的数字,也没有正确分开。
答案 0 :(得分:3)
这样做
string.scan(/[\d,]+/)
答案 1 :(得分:1)
另一种方法是删除不需要的字符。
arr = ["This is a number 123,124,123",
"These are some more numbers 123,345,123; 231,123,123; 124,152,123",
"This one is an odd situation 123,124,125; 123,123,123; more text"]
arr.map { |str| str.gsub(/[^\s\d,]+/,'').split }
#=> [["123,124,123"],
# ["123,345,123", "231,123,123", "124,152,123"],
# ["123,124,125", "123,123,123"]]
答案 2 :(得分:-1)
与您的号码匹配的正则表达式为\d{1,3}(,\d{3})*