1

Possible Duplicate:
Regex for IP address

There is a regular expression match IPv6 AND IPv4 ?
Or, just IPv6 ?

For validation mask in a DevExpress UI control.

Thanks.

Community
  • 1
  • 1
Jacob
  • 751
  • 1
  • 6
  • 18

3 Answers3

5

I know you asked for a Regular Expression but you might want to consider using the System.Net.IPAddress.TryParse method instead.

Robert
  • 3,328
  • 2
  • 24
  • 25
  • how he use parse in regex field of control? – burning_LEGION Sep 27 '12 at 10:36
  • thanks, but i need it for validation mask in a DevExpress UI control. its a String. – Jacob Sep 27 '12 at 10:40
  • 1
    The TryParse method accepts a string and returns a bool, it uses an out param to return the IPAddress object. http://msdn.microsoft.com/en-us/library/system.net.ipaddress.tryparse.aspx – Robert Sep 27 '12 at 11:21
  • You don't need to use the out value and it will parse either v4 or v6. – Robert Sep 27 '12 at 11:23
  • i see, but in my scenario i need a String of Regular Expression in purpose to set it into a String Property of a UI Control as a Validation Mask. there is no input until its pass the validation, so i cant use System.Net.IPAddress.TryParse method – Jacob Sep 27 '12 at 11:52
2

The IP4 one can look like "(0?0?[1-9]|0?[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-4])(\.(0?0?[0-9]|0?[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-4])){2}(\.(0?0?[1-9]|0?[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))"

this allows for 0's too, eg 010.000.000.001 .. (cos someone in our place thought it smart to do it)

BugFinder
  • 17,474
  • 4
  • 36
  • 51
0

it's really long regex =) first row for ip4, rest is ip6

((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)|
((\A([0-9a-f]{1,4}:){1,1}(:[0-9a-f]{1,4}){1,6}\Z)|
(\A([0-9a-f]{1,4}:){1,2}(:[0-9a-f]{1,4}){1,5}\Z)|
(\A([0-9a-f]{1,4}:){1,3}(:[0-9a-f]{1,4}){1,4}\Z)|
(\A([0-9a-f]{1,4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