user348173
user348173

Reputation: 9278

Find number in string

How to find number(int, float) in a string (fast method)?
For example: "Question 1" and "Question 2.1". I need that in variable would be only number.
Thanks.

Upvotes: 0

Views: 2925

Answers (4)

Amir Ismail
Amir Ismail

Reputation: 3883

you can use this ([0-9]\.*)*[0-9] regex to get it. you can test any regex here

Edit

this sample code in C#

Regex regexpattern = new Regex(@"(([0-9]\.*)*[0-9])");
String test = @"Question 1 and Question 2.1.3";
foreach (Match match in regexpattern.Matches(test))
{
    String language = match.Groups[1].Value;
}

Upvotes: 3

Kirill Polishchuk
Kirill Polishchuk

Reputation: 56162

Use this regex: \d+(?:\.\d+)?.

Upvotes: 1

Skizz
Skizz

Reputation: 71070

There's always the good ol' regular expressions! It wouldn't give you a float for "2.1" though, but I'm not sure that's a good idea since there's always the possibility of "2.1.4" or even "2a". Might be best to store a vector of numbers for each item.

Upvotes: 1

Sergey Shulik
Sergey Shulik

Reputation: 1010

You can use Reqular Expressions. To search numbers try this:

var r = System.Text.RegularExpressions.Regex.Match("Question 2.1", "\d+");

Upvotes: 1

Related Questions