1

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

2
  • For q2, you will have one match per string of ints Commented Oct 19, 2011 at 19:39
  • The Java Matcher.matches() method works as you expect, however the .Net Match() function returns the first substring that matches your pattern, and the Matches() function returns "all" (though not as you might expect) substrings that match your pattern. You simply need to use ^ and $ anchors as specified in all the answers Commented Oct 19, 2011 at 19:53

3 Answers 3

3
  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]+");
    
Sign up to request clarification or add additional context in comments.

Comments

1

it says that it has found it.

if you want the whole expression to be checked so :

^[0-9]+$

Comments

0

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

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.