幫助

Java中各種正則表達(dá)式驗(yàn)證[郵箱、密碼前后空格、日期合法、IP]

2023-04-18 10:51 技術(shù)文檔

一、驗(yàn)證郵箱是否正確

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-]+)+$"));


}


}

二、驗(yàn)證密碼的開始或結(jié)尾不能為空格


密碼的開始不能為空格:password.matches("^\\s+.*");

密碼的結(jié)束不能為空格: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());

}


}


四、驗(yàn)證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"); //以驗(yàn)證127.400.600.2為例

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

}


}

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

版權(quán)聲明:本文為CSDN博主「NeverGiveUp7」的原創(chuàng)文章,遵循CC 4.0 BY-SA版權(quán)協(xié)議,轉(zhuǎn)載請(qǐng)附上原文出處鏈接及本聲明。

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



相關(guān)推薦

QQ在線咨詢