一個簡單的例子,郵箱地址檢驗:
假設一個簡單的郵箱地址的格式爲:字符 @ 字符 . com(或net.cn)
如:
[email protected]
[email protected]
要對一個郵箱地址進行大致檢驗,利用正則表達式:
\\w+@\\w+\\.(com|net.cn)
\\w
轉義爲\w
,表示字母、數字、下劃線,所以\w+
代表多個字母、數字、下劃線
@
匹配地址中的@
\\.
轉義爲.
(com|net.cn)
表示以com或net.cn結尾
完整代碼:
/**
* This is a simple version of a Mail_Address_Judge program.
* Practice the use of package of regex
*
* @author Pro_ALK416
*/
package RegexPractice;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
//import java.awt.Frame;
public class MailJudge {
public static void main(String args[]){
Scanner scan1=new Scanner(System.in);
String targstr;
Matcher match1; // " \\. " actually mean "."
String regexstr="\\w+@\\w+\\.(com|net.cn)"; // the regexstr is : \w+ @ \w+ . (com|net.cn)
Pattern pat1=Pattern.compile(regexstr);
System.out.println("Input the address of the mail to see if it is a legal mail adress");
System.out.print("\n\n\nInput : ");
targstr=scan1.next();
match1=pat1.matcher(targstr);
if(match1.find()){
System.out.println("This is a legal adress");
}
else{
System.out.println("This is not a legal adress!");
}
scan1.close();
}
}
/**Result:
Input : [email protected]
This is a legal adress
Input : [email protected]
This is a legal adress
Input : Altria456.net.cn
This is not a legal adress!
*/
有關的正則表達式知識:
邏輯表達 | 意義 |
---|---|
XY | Y緊跟X |
X/Y(這裏表達或的意思) | X或Y |
(X) | 將X視爲一個整體 |
例如:
Altri | a 表示Altri或 Altra
Altria | a均表示Altria
(Altria) | a表示Altria或a
(預定義的)字符表示 | 意義 |
---|---|
\d | 數字:[0-9] |
\D | 非數字: [^0-9] |
\w | 表示字母、數字、下劃線,[a-zA-Z_0-9] |
\W | 表示不是由字母、數字、下劃線組成 [^/w] |
\s | 空白字符:[ /t/n/x0B/f/r] |
\S | 非空白字符:[^/s] |
. | 任何字符(與行結束符可能匹配也可能不匹配) |
參考博客 | Click Here |
字符類 | |
---|---|
[abc] | 表示可能是a,可能是b,也可能是c |
[^abc] | 表示不是a,b,c中的任意一個 |
[a-zA-Z] | 表示是英文字母 |
[0-9] | 表示是數字 |
[a-d[m-p]] | a 到 d 或 m 到 p |
[a-z&&[^bc]] | a 到 z,除了 b 和 c |
[a-z&&[^m-p]] | a 到 z,而非 m 到 p |
參考博客 | Click Here |
傳送門:
Regex入門1: Click Here