帮助

Java中各种正则表达式验证[邮箱、密码前后空格、日期合法、IP]

2023-04-18 10:51 技术文档

一、验证邮箱是否正确

public class ForTest {


public static void main(String[] args) {


System.out.println("123");


String email = "gengxiaopeng@hyper-telecom.com";


//boolean ss = email.matches("^[\\w-]+(\\.[\\w-]+)*@[\\w-]+(\\.[\\w-]+)+$");


System.out.print(email.matches("^[\\w-]+(\\.[\\w-]+)*@[\\w-]+(\\.[\\w-]+)+$"));


}


}

二、验证密码的开始或结尾不能为空格


密码的开始不能为空格:password.matches("^\\s+.*");

密码的结束不能为空格:password.matches(".*\\s+$")


三、判断给出的日期是否合法


import java.util.regex.Matcher;

import java.util.regex.Pattern;


public class ForTest {


public static void main(String[] args) {


Pattern pattern = Pattern.compile("^((\\d{2}(([02468][048])|([13579][26]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))(\\s(((0?[0-9])|([1-2][0-3]))\\:([0-5]?[0-9])((\\s)|(\\:([0-5]?[0-9])))))?$");


Matcher matcher = pattern.matcher("2015-04-30 23:59:59");


System.out.println(matcher.matches());

}


}


四、验证IP地址是否合法:255.255.255.255

import java.util.regex.Matcher;


import java.util.regex.Pattern;


public class ForTest {

public static void main(String[] args) {

Pattern pattern1 = Pattern.compile("\\b((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\b");

Matcher matcher1 = pattern1.matcher("127.400.600.2"); //以验证127.400.600.2为例

System.out.println(matcher1.matches());

}


}

————————————————

版权声明:本文为CSDN博主「NeverGiveUp7」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。

原文链接:https://blog.csdn.net/gengxiaoming7/article/details/47979281



相关推荐

QQ在线咨询