tags:

views:

46

answers:

3

Let us say that I have a string "ABCDEF34GHIJKL". How would I extract the number (in this case 34) from the string using regular expressions?

I know little about the regular expressions, and while I would love to learn all there is to know about it, time constraints have forced me to simply find out how this specific example would work.

Any information would be greatly appreciated!

Thanks

A: 

Depends on the language, but you want to match with an expression like ([0-9]+). That will find (the first group of) digits in the string. If your regexp engine expects to starts matching at the start of the string, you will need to add .*?([0-9]+).

calmh
+4  A: 

This is a very language specific question but you didn't specify a language. Based on previous questions you've asked though I'm going to assume you meant this to be a C# language question.

For this scenario just write up a regex for a number and apply it to the input.

var match = Regex.Match(input, "\d+");
if ( match.Success ) {
  var number = match.Value;
}
JaredPar
A: 

I agree with calmh ([0-9]+) is the main thing need to worry about. However you may want to note that in a lot of languages you'll need to use back references (usually \\1 or \1) to get the value. For example

"ABCDEF34GHIJKL".sub(/^.*?([0-9]+).*$/, "\\1")

A better solution in Ruby however would be the following and would also match multiple numbers in the string.

"ABCDEF34GHIJ1001KL".scan(/[0-9]+/) { |m|
    puts m
}

# Outputs:
34
1001

Most languages have some sort of similar methods. There are some examples of various languages here http://www.regular-expressions.info/tools.html as well as some good examples of back references being used.

Jamie