从字符串中获取数字

时间:2009-07-30 12:48:51

标签: ruby regex

我收到了一个字符串:

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

我想获取第一个管道(|)之间的数字,返回“2 3 4 5”。

任何人都可以帮助我使用正则表达式吗?

3 个答案:

答案 0 :(得分:8)

这有用吗?

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

答案 1 :(得分:6)

如果你只想要数字,

Arun's answer是完美的。 即

"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"]

答案 2 :(得分:0)

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

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

然后

\d

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

相关问题