Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to extract numbers from a string

Tags:

.net

regex

Can somebody help me construct this regular expression please...

Given the following strings...

  • "April ( 123 widgets less 456 sprockets )"
  • "May (789 widgets less 012 sprockets)"

I need a regular expression that will extract the two numbers from the text. The month name will vary. The brackets, "widgets less" and "sprockets" text is not expected to change between strings, however it would be really useful if this text was able to be varied as well.

like image 972
Martin Robins Avatar asked Nov 15 '10 17:11

Martin Robins


People also ask

How do I capture a number in regex?

\d for single or multiple digit numbers 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. [1-9][0-9] will match double digit number from 10 to 99.

How do you only extract a number from a string in Python?

To find numbers from a given string in Python we can easily apply the isdigit() method. In Python the isdigit() method returns True if all the digit characters contain in the input string and this function extracts the digits from the string.

How do I find all the numbers in a 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. [0-9]+ represents continuous digit sequences of any length.


1 Answers

if you know for sure that there are only going to be 2 places where you have a list of digits in your string and that is the only thing you are going to pull out then you should be able to simply use

\d+ 
like image 83
Seattle Leonard Avatar answered Nov 05 '22 08:11

Seattle Leonard