Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using regex to extract multiple numbers from strings

Tags:

c#

.net

regex

I have a string with two or more numbers. Here are a few examples:

"(1920x1080)"
" 1920 by 1080"
"16 : 9"

How can I extract separate numbers like "1920" and "1080" from it, assuming they will just be separated by one or more non-numeric character(s)?

like image 211
David Avatar asked May 31 '12 11:05

David


People also ask

How extract all numbers from string in regex?

Python Regex – Get List of all Numbers from String. To get the list of all numbers in a String, use the regular expression '[0-9]+' with re. findall() method. [0-9] represents a regular expression to match a single digit in the string.

How do I capture a number in regex?

To match any number from 0 to 9 we use \d in regex. It will match any single digit number from 0 to 9. \d means [0-9] or match any number from 0 to 9. Instead of writing 0123456789 the shorthand version is [0-9] where [] is used for character range.

How do I extract all 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.

Can you use regex with numbers?

Since regular expressions work with text, a regular expression engine treats 0 as a single character, and 255 as three characters. To match all characters from 0 to 255, we'll need a regex that matches between one and three characters. The regex [0-9] matches single-digit numbers 0 to 9.


2 Answers

The basic regular expression would be:

[0-9]+

You will need to use the library to go over all matches and get their values.

var matches = Regex.Matches(myString, "[0-9]+");

foreach(var march in matches)
{
   // match.Value will contain one of the matches
}
like image 72
Oded Avatar answered Oct 14 '22 01:10

Oded


You can get the string by following

MatchCollection v = Regex.Matches(input, "[0-9]+");
foreach (Match s in v)
            {
                // output is s.Value
            }
like image 40
Md Kamruzzaman Sarker Avatar answered Oct 14 '22 00:10

Md Kamruzzaman Sarker