从字符串中获取数字

5

I got a string:

"1|2 3 4 oh 5 oh oh|e eewrewr|7|".

我希望能够获取第一个竖线(|)之间的数字,返回结果为“2 3 4 5”。

有人能帮我写正则表达式来实现吗?


当使用分割操作足够时,不要使用正则表达式。 - Brian
3个回答

8

这个可以工作吗?

"1|2 3 4 oh 5 oh oh|e eewrewr|7|".split('|')[1].scan(/\d/)

这行代码的作用是将字符串中第二个以“|”分隔的元素取出来,然后匹配其中的数字并返回一个数组。

2
...而要获取数字,而不是字符串,您可以附加这个:.map{|n| n.to_i} - Nate Kohl
...并且对于一个字符串中的数字,就像你的例子一样,你可以使用.join(' ')来添加。 - Pesto
@Nate: .map!{|n| n.to_i} 怎么样?(个人而言,我喜欢改变原对象而不是获得新对象) - Swanand
"1|2 3 4 oh 54 5 oh oh|e eewrewr|7|" 将返回:["2", "3", "4", "5", "4", "5"] - Swanand
使用以下代码替换原有代码:"1|2 3 4 oh 55 oh oh|e eewrewr|7|".split('|')[1].scan(/\d+/) - Swanand

6
如果你只想要数字,Arun的回答是完美的。 即。
"1|2 3 4 oh 5 oh oh|e eewrewr|7|".split('|')[1].scan(/\d/)
 # Will return ["2", "3", "4", "5"]
"1|2 3 4 oh 55 oh oh|e eewrewr|7|".split('|')[1].scan(/\d/)
 # Will return ["2", "3", "4", "5", "5"]

如果您希望得到数字,可以这样做:
# Just adding a '+' in the regex:
"1|2 3 4 oh 55 oh oh|e eewrewr|7|".split('|')[1].scan(/\d+/)
# Will return ["2", "3", "4", "55"]

0

如果你只想使用正则表达式...

\|[\d\s\w]+\|

然后

\d

但这可能不是最好的解决方案


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接