Regular expression for matching IP subnet

I need a C # regular expression that will match an IP subnet, such as "127.65.231", but does not match an IP address on the subnet, such as "127.65.231.111". I found this regex for the IP address:

@ "\ B \ r {1,3}. \ D {1,3}. \ D {1,3}. \ D {1,3} \ b"

and thought that I can just delete the part that checks the last octet, for example:

@ "\ B \ r {1,3}. \ R {1,3}. \ R {1,3} \ b"

but this matches both the IP address and the subnet. Can anyone help with this?

+4
source share
2 answers
@"^\d{1,3}\.\d{1,3}\.\d{1,3}$" 

use Line Anchors. Add ^ to the beginning of your Regex and $ at the end to check the beginning and end of the input.

This will correspond to 127.65.231 , but not 127.65.231.111

0
source

You can try using lookahead. Also, avoid characters . : - otherwise it will match any character:

 @"\b\d{1,3}\.\d{1,3}\.\d{1,3}(?=\.\d{1,3})\b" 

This will match any string, such as 127.65.231 , if accompanied by a string of type .111 .

+1
source

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


All Articles