一个简单的例子,邮箱地址检验:
假设一个简单的邮箱地址的格式为:字符 @ 字符 . com(或net.cn)
如:
abcdefg@qq.com
ABCDEFG@yahoo.com
要对一个邮箱地址进行大致检验,利用正则表达式:
\\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 : ABCDEF@qq.com
This is a legal adress
Input : Altria123@ALK.net.cn
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