Regex allows you to add characters

When trying to write an expression in C #, the Regex expression is correct and matches the line:

String telRegex = @"(^0[0-9]{10})|(\(0[0-9]{4}\)[0-9]{6}$)";
Match telRegexResult = Regex.Match(textBox1.Text, telRegex);
if (telRegexResult.Success) {
    MessageBox.Show("Your Regex Matches!");
} else MessageBox.Show("Your Regex doesn't match!");

If I put “01446847362”, it will show that the regular expression matches, which is the intended result, but if I also put “01446847362word”, it will also show that it is correct.

Is there anything I can add to my regex to disable it?

+4
source share
2 answers

Your regex has alternation, which means it captures:

^0[0-9]{10}

Or:

\(0[0-9]{4}\)[0-9]{6}$

, , ^ , $ , .

, ^ $ ( ):

String telRegex = @"^((0[0-9]{10})|(\(0[0-9]{4}\)[0-9]{6}))$";
+5

. , @Iridium one, , Regex :

string pattern = @"^0(?'p'\()?[0-9]{4}(?('p')\))[0-9]{6}$";
0

Source: https://habr.com/ru/post/1692863/


All Articles