Sebastian
Sebastian

Reputation: 2786

Get numbers from string

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?

Upvotes: 5

Views: 7455

Answers (3)

Swanand
Swanand

Reputation: 12426

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

Upvotes: 6

Brian Hicks
Brian Hicks

Reputation: 6413

if you want to use just regex...

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

and then

\d

but that's probably not the best solution

Upvotes: 0

Arun
Arun

Reputation: 118

Does this work?

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

Upvotes: 8

Related Questions