1

I am new to C# and working with regular expressions. I have created a regex accurately and have tested online but when I use that regex in my function it always validate it as success case.

Here is my code:

 Regex regex = new Regex(@"[+]?[0-9]+");
        Match match = regex.Match(phone);
        if (match.Success)
        {
            return true;
        }
        else
        {
            return false;
        }

and I am using this number to validate : +92-322-4995562 which must be invalid according to my regex but it is returning me as match case. Please help

Bilal Amjad
  • 232
  • 2
  • 13

2 Answers2

3

No, it isn't wrong because you're not anchoring the pattern.

This allows the regex engine to find a position inside the input where the pattern matches, and not be forced to check if the entire input matches.

Specifically, this pattern:

[+]?[0-9]+

Matches this part:

+92-322-4995562
^^^

To ensure it checks against the whole input you must "anchor" it by specifying that the start of the pattern has to coincide with the start of the input, and that the end of the pattern has to coincide with the end of the input.

You do this with a pattern like this:

^....$

The ^ character anchors to the start of the input and $ to the end of the input.

So your final pattern should look like this:

^[+]?[0-9]+$
Lasse V. Karlsen
  • 380,855
  • 102
  • 628
  • 825
1

try this
^[+]?[0-9]+$ or ^\+?\d+$

Explanation:
^ assert position at start of the string
\+ matches the character +
\d match a digit [0-9]
$ assert position at end of the string

Tim007
  • 2,557
  • 1
  • 11
  • 20