[.net] Regular expression to extract numbers from a string

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.

Thanks in advance.

This question is related to .net regex

The answer is


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+

^\s*(\w+)\s*\(\s*(\d+)\D+(\d+)\D+\)\s*$

should work. After the match, backreference 1 will contain the month, backreference 2 will contain the first number and backreference 3 the second number.

Explanation:

^     # start of string
\s*   # optional whitespace
(\w+) # one or more alphanumeric characters, capture the match
\s*   # optional whitespace
\(    # a (
\s*   # optional whitespace
(\d+) # a number, capture the match
\D+   # one or more non-digits
(\d+) # a number, capture the match
\D+   # one or more non-digits
\)    # a )
\s*   # optional whitespace
$     # end of string

you could use something like:

[^0-9]+([0-9]+)[^0-9]+([0-9]+).+

Then get the first and second capture groups.


we can use \b as a word boundary and then; \b\d+\b