Why is this C # regex not working?

I tried to write an expression to test the following pattern:

digit [0-9] 1 time for sure
"Point"
digit [0-9] 1-2 times
"Point"
digit [0-9] 1-3 times
"Point"
number [0-9] 1-3 times or β€œhyphen”

For example, these are legal numbers:

1.10.23.5 1.10.23.- 

is not:

 10.10.23.5 1.254.25.3 

I used RegexBuddy to write the following pattern:

 [0-9]\.[0-9]{1,2}\.[0-9]{1,3}\.[0-9]{1,3}|[0-9]\.[0-9]{1,2}\.[0-9]{1,3}\.- 

Everything seems perfect in RegexBuddy, but in my code I believe in illegal numbers (e.g. 10.1.1.1)

I wrote the following method to test this pattern:

  public static bool IsVaildEc(string ec) { try { if (String.IsNullOrEmpty(ec)) return false; string pattern = @"[0-9]\.[0-9]{1,2}\.[0-9]{1,3}\.[0-9]{1,3}|[0-9]\.[0-9]{1,2}\.[0-9]{1,3}\.-"; Regex check = new Regex(pattern); return check.IsMatch(ec); } catch (Exception ex) { //logger } } 

What am I doing wrong?

+4
source share
4 answers

You regex are not tied to the beginning and end of a line, so it also matches a substring (e.g. 0.1.1.1 on line 10.1.1.1 ).

As you can see, RegexBuddy matches the substring in the first "illegal" number. It does not correctly match the second number, because the three digits in the second octet cannot be matched at all:

RegexBuddy Screenshot

 string pattern = @"^(?:[0-9]\.[0-9]{1,2}\.[0-9]{1,3}\.[0-9]{1,3}|[0-9]\.[0-9]{1,2}\.[0-9]{1,3}\.-)$"; 

will fix this problem.

Then your regular expression is unnecessarily complicated. The following does the same thing, but easier:

 string pattern = @"^[0-9]\.[0-9]{1,2}\.[0-9]{1,3}\.(?:[0-9]{1,3}|-)$"; 
+9
source

to try:

 @"^[0-9]\.[0-9]{1,2}\.[0-9]{1,3}\.[0-9]{1,3}|[0-9]\.[0-9]{1,2}\.[0-9]{1,3}\.-" 

you do not start at the beginning of the text

0
source

If you match "10.1.1.1", "0.1.1.1" part of your string will be the correct number and will return true for this.

Conformity

 @"^[0-9]\.[0-9]{1,2}\.[0-9]{1,3}\.[0-9]{1,3}|[0-9]\.[0-9]{1,2}\.[0-9]{1,3}\.-" 

with a ^ in the beginning means you want to match the beginning.

0
source

You are missing ^ char at the beginning of the regex.

Try this regex:

 ^[0-9]\.[0-9]{1,2}\.[0-9]{1,3}\.[0-9]{1,3}|[0-9]\.[0-9]{1,2}\.[0-9]{1,3}\.- 

This C # Regex Cheat Sheet May Be Convenient

0
source

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


All Articles