What are the Java regular expressions for matching IPv4 and IPv6 strings?

前端 未结 6 1830
抹茶落季
抹茶落季 2020-12-03 18:57

Looking for a string to pass to String#matches(String) that will match IPv4, and another to match IPv6.

6条回答
  •  既然无缘
    2020-12-03 19:50

    Here's a regex to match IPv4 addresses:

    \b(?:(?: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]?)\b
    

    You'll need to escape the backslashes when you specify it as a string literal in Java:

    "\\b(?:(?: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]?)\\b"
    

提交回复
热议问题