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)?
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.
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.
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.
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.
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
}
You can get the string by following
MatchCollection v = Regex.Matches(input, "[0-9]+");
foreach (Match s in v)
{
// output is s.Value
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With