我想使用regex验证有或没有端口号的IP地址。我的输入字符串应该是IP:PORT或IP。我只想要一个regex,它将验证IP:PORT或IP两者。
我的IP地址regex是:
^(?:(?:1\d?\d|[1-9]?\d|2[0-4]\d|25[0-5])\.){3}(?:1\d?\d|[1-9]?\d|2[0-4]\d|25[0-5])$有人能告诉我如何将可选的端口号添加到这个现有的regex中吗?
发布于 2013-05-06 23:45:37
为什么这么复杂:谷歌搜索:http://answers.oreilly.com/topic/318-how-to-match-ipv4-addresses-with-regular-expressions/
你也试图在一个地方做太多的事情。使用正则表达式做好它的工作,然后在不适合使用正则表达式的地方使用其他智能工具。在您的示例中,不要尝试在正则表达式中验证IP地址的取值范围,而是在后期处理中进行验证:
.... ^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(:(\d{1,5}))?$
byte[] ip = new byte[4];
for (int i = 1; i <= 4; i++) {
int bt = Integer.parseInt(matcher.group(i));
if (bt < 0 || bt > 255) {
throw new IllegalArgumentException("Byte value " + bt + " is not valid.");
}
ip[i-1] = (byte)bt;
}
integer port = 0;
if (matcher.group(6) != null) {
port = Integer.parseInt(matcher.group(6));
}发布于 2013-05-06 23:46:18
这是可行的。
^(?:(?:1\d?\d|[1-9]?\d|2[0-4]\d|25[0-5])\.){3}(?:1\d?\d|[1-9]?\d|2[0-4]\d|25[0-5])(?:[:]\d+)?$ 发布于 2017-07-17 20:57:44
类解决方案{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
while(in.hasNext()){
String IP = in.next();
System.out.println(IP.matches(new MyRegex().pattern));
}
}}
类MyRegex {
String pattern="^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
"([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
"([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
"([01]?\\d\\d?|2[0-4]\\d|25[0-5])$";
}私有静态最终字符串IPADDRESS_PATTERN =
"^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
"([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
"([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
"([01]?\\d\\d?|2[0-4]\\d|25[0-5])$";ı在这个网站上使用了这个解决方案:
https://www.mkyong.com/regular-expressions/how-to-validate-ip-address-with-regular-expression/
https://stackoverflow.com/questions/16402078
复制相似问题