tags:

views:

167

answers:

3

Hi.

I got a string:

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

I want to get the digits between first pipes (|), returning "2 3 4 5".

Can anyone help me with the regular expression to do that?

+5  A: 

Does this work?

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

Arun
...and to get numbers, instead of strings, you could append this: .map{|n| n.to_i}
Nate Kohl
... and to the numbers in one string as in your example, you append this instead: `.join(' ')`
Pesto
@Nate: How about `.map!{|n| n.to_i}` (Personally, I like to mutate rather than get a new object)
Swanand
"1|2 3 4 oh 54 5 oh oh|e eewrewr|7|" will return you: ["2", "3", "4", "5", "4", "5"]
Swanand
Use this instead: "1|2 3 4 oh 55 oh oh|e eewrewr|7|".split('|')[1].scan(/\d+/)
Swanand
A: 

if you want to use just regex...

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

and then

\d

but that's probably not the best solution

Reactor5
+1  A: 

Arun's answer is perfect if you want only digits. i.e.

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

If you want numbers instead,

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