简体   繁体   中英

Regular Expression to match IP address + wildcard

I'm trying to use a RegularexpressionValidator to match an IP address (with possible wildcards) for an IP filtering system.

I'm using the following Regex:

"([0-9]{1,3}\\.|\\*\\.){3}([0-9]{1,3}|\\*){1}"

Which works fine when running it in LINQPad with Regex.Matches, but doesn't seem to work when I'm using the validator.

Does anyone have a suggestion as to either a better Regex or why it would work in test but not in situ?

Cheers, Ed

This: \\\\.|\\\\*\\\\. looks like the dodgy bit. Do this instead:

@"^(([0-9]{1,3}|\*)\.){3}([0-9]{1,3}|\*)$"

And to only accept 0-255 (thanks, apoorv020 ):

^((([0-9]{1,2})|(1[0-9]{2,2})|(2[0-4][0-9])|(25[0-5])|\*)\.){3}(([0-9]{1,2})|(1[0-9]{2,2})|(2[0-4][0-9])|(25[0-5])|\*)$

asp:RegularExpressionValidator does not require you to double-escape backslashes. You should try:

([0-9]{1,3}\\.|\\*\\.){3}([0-9]{1,3}|\\*){1}

[0-9]{1,3} would allow IP addresses of the form 999.999.999.999 . Your IP address range should allow only 0-255.
Replace all occurences of [0-9]{1,3} with ([0-9]{1,2})|(1[0-9]{2,2})|(2[0-4][0-9])|(25[0-5])
This does seem very complicated to me, and probably there are better ways of doing this, but it seems correct at first glance.

如何在表达式上放置开始和结束字符串字符

^([0-9]{1,3}\\.|\\*\\.){3}([0-9]{1,3}|\\*){1}$

My answer is general for .NET, not RegularExpressionValidator -specific.

Regex string for IP matching (use ExplicitCapture to avoid useless capturing and keep RE concise):

"\\b0*(2(5[0-5]|[0-4]\\d)|1?\\d{1,2})(\\.0*(2(5[0-5]|[0-4]\\d)|1?\\d{1,2})){3}\\b"

Depending on particular use case you may want to add appropriate anchors, ie \\A or ^ at the beginning and \\Z or $ at the end. Then you can remove word-boundaries requirement: \\b .

(Remember about doubling \\ inside the string)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM