以下代碼是判斷字元串是否為郵箱的正确格式.
public static void main(String[] args) {
/*
* [email protected]
* [0-9a-zA-Z_]+@[0-9a-zA-Z]+(\.[a-zA-Z]+)+
*
* boolean matches(String regex)
* 比對目前字元串是否符合給定的正規表達式的格式要求
*/
String mail = "[email protected]";
String regex = "[0-9a-zA-Z_]+@[0-9a-zA-Z]+(\\.[a-zA-Z]+)+";
boolean match = mail.matches(regex);
if(match) {
System.out.println("是郵箱!");
}else {
System.out.println("不是郵箱!");
}
}
然後我們也可以将目前字元串按照滿足正規表達式的部分替換為給定字元串
public static void main(String[] args) {
String str = "abc123def456ghi";
/*
* 将目前字元串中的數字部分替換為#NUMBER#
* abc#NUMBER#def#NUMBER#ghi
*/
str =str.replaceAll("[0-9]+", "#NUMBER#");
System.out.println(str);
}
接下來的這段代碼是和諧用語,将所輸入的髒話轉為**,不管是幾位的髒話都轉為兩個星号,防止有些人想要去猜别人究竟罵的是什麼
public static void main(String[] args) {
String regex = "(wqnmlgb|cnm|sb|mdzz|nc|djb|nmsl|ngdsb|wc)";
String message = "wc!你個sb!你怎麼這麼nc!你就一個djb!";
message = message.replaceAll(regex, "**");
System.out.println(message);
}
運作結果就是這樣的:
String[] split (String regex)
将目前字元串中按照滿足正規表達式的部分進行拆分,
并将拆分後的若幹段字元串以數組形式傳回
String str = "abc123def456ghi";
/*
* 将目前字元串按照數字部分進行拆分,得到所有的字母部分
*/
String[] data =str.split("[0-9]+");
System.out.println(data.length);
for(int i=0;i<data.length;i++){
System.out.println(data[i]);
}
運作結果如下圖
根據 Java Language Specification 的要求,Java 源代碼的字元串中的反斜線被解釋為 Unicode 轉義或其他字元轉義。是以必須在字元串字面值中使用兩個反斜線,表示正規表達式受到保護,不被 Java 位元組碼編譯器解釋。例如,當解釋為正規表達式時,字元串字面值 “\b” 與單個倒退字元比對,而 “\\b” 與單詞邊界比對。字元串字面值 “\(hello\)” 是非法的,将導緻編譯時錯誤;要與字元串 (hello) 比對,必須使用字元串字面值 “\\(hello\\)”。