1

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

1
  • What language are you using RexEx with? Commented Apr 2, 2010 at 21:14

3 Answers 3

4

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;
}
Sign up to request clarification or add additional context in comments.

Comments

0

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]+).

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.