Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get numbers from string

Tags:

regex

ruby

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?

like image 295
Sebastian Avatar asked Jul 30 '09 12:07

Sebastian


People also ask

How do you get number from a string excel?

Extract Numbers from String in Excel (using VBA) Since we have done all the heavy lifting in the code itself, all you need to do is use the formula =GetNumeric(A2). This will instantly give you only the numeric part of the string. Note that since the workbook now has VBA code in it, you need to save it with .

How do I extract numbers from a string in Python?

This problem can be solved by using split function to convert string to list and then the list comprehension which can help us iterating through the list and isdigit function helps to get the digit out of a string.


2 Answers

Does this work?

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

like image 200
Arun Avatar answered Nov 26 '22 07:11

Arun


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"]
like image 24
Swanand Avatar answered Nov 26 '22 08:11

Swanand