dattebayo
dattebayo

Reputation: 2072

Regular expression for numbers in string

The input string "134.45sdfsf" passed to the following statement

System.Text.RegularExpressions.Regex.Match(input, pattern).Success;

returns true for following patterns.

pattern = "[0-9]+"

pattern = "\\d+"

Q1) I am like, what the hell! I am specifying only digits, and not special characters or alphabets. So what is wrong with my pattern, if I were to get false returned value with the above code statement.

Q2) Once I get the right pattern to match just the digits, how do I extract all the numbers in a string? Lets say for now I just want to get the integers in a string in the format "int.int^int" (for example, "11111.222^3333", In this case, I want extract the strings "11111", "222" and "3333").

Any idea?

Thanks

Upvotes: 1

Views: 277

Answers (3)

Fischermaen
Fischermaen

Reputation: 12458

Q1) Both patterns are correct.

Q2) Assuming you are looking for a number pattern "5 digits-dot-3 digits-^-4 digits" - here is what your looking for:

        var regex = new Regex("(?<first>[0-9]{5})\.(?<second>[0-9]{3})\^(?<third>[0-9]{4})");
        var match = regex.Match("11111.222^3333");
        Debug.Print(match.Groups["first"].ToString());
        Debug.Print(match.Groups["second"].ToString            
        Debug.Print(match.Groups["third"].ToString

I prefer named capture groups - they will give a more clear way to acces than

Upvotes: 0

vcsjones
vcsjones

Reputation: 141588

  1. You are specifying that it contains at least one digit anywhere, not they are all digits. You are looking for the expression ^\d+$. The ^ and $ denote the start and end of the string, respectively. You can read up more on that here.

  2. Use Regex.Split to split by any non-digit strings. For example:

    string input = "123&$456";
    var isAllDigit = Regex.IsMatch(input, @"^\d+$");
    var numbers = Regex.Split(input, @"[^\d]+");
    

Upvotes: 3

Royi Namir
Royi Namir

Reputation: 148524

it says that it has found it.

if you want the whole expression to be checked so :

^[0-9]+$

Upvotes: 1

Related Questions