Kevin
Kevin

Reputation: 4848

Get numbers from a string with RegEx

I have a string that could look like this:

"Lesson 2.3"

or this:

"Lesson 12.5"

Is there any way I can just grab the 2.3 or 12.5 or any other number with the same format from this string? I'm not trying to turn it into a double or float, I just want the string part that has the numbers in it, i.e. "2.3" or "12.5".

I've tried using RegEx, but my attempt is only returning the first number:

var number = Regex.Match(lessonTopicName, "\\d+").Value; // returns "2"

I don't have a complete understanding of RegEx, so I know I'm doing this wrong. I'd like to write a method where I can just pass in the string and it returns the numbers from the string in string format, if that makes sense.

Upvotes: 0

Views: 114

Answers (3)

DamianM
DamianM

Reputation: 498

var number = Regex.Match(lessonTopicName, @"\d+.\d+").Value;

Upvotes: 0

Matt Cremeens
Matt Cremeens

Reputation: 5151

What about

var number = Regex.Match(lessonTopicName, "[0-9]+.[0-9]$").Value;

Upvotes: 0

driis
driis

Reputation: 164281

\d+ matches digits only. You need to match the period as well:

var number = Regex.Match(lessonTopicName, "\\d+\\.?\\d*").Value; 

The period and following digits is made optional here by ? (0 or 1) and * (0 or more). If you need to require a period and a decimal after it, that version would be:

var number = Regex.Match(lessonTopicName, "\\d+\\.\\d+").Value; 

Upvotes: 3

Related Questions