一、用java语言来匹配正则表达式可以分为以下步骤:
1、根据需要构造正则表达式字符串,假设为reg;
2、用 Pattern 类的 compile() 方法编译正则表达式,Pattern pattern = Pattern.compile(reg);
3、调用 Pattern 对象的 matcher() 方法来获得一个 Matcher 对象;
4、调用 Matcher 对象的 matches() 方法即可获得是否匹配的boolean值;
二、Pattern类和Matcher类说明:
1、Pattern 类:
pattern 对象是一个正则表达式的编译表示。Pattern 类没有公共构造方法。要创建一个 Pattern 对象,你必须首先调用其公共静态编译方法,它返回一个 Pattern 对象。该方法接受一个正则表达式作为它的第一个参数。
2、Matcher 类:
Matcher 对象是对输入字符串进行解释和匹配操作的引擎。与Pattern 类一样,Matcher 也没有公共构造方法。你需要调用 Pattern 对象的 matcher 方法来获得一个 Matcher 对象。
三、常用正则表达式
1、邮箱
[a-zA-Z_]{1,}[0-9]{0,}@(([a-zA-Z0-9]-*){1,}\.){1,3}[a-zA-Z\-]{1,}
2、一个或多个汉字
^[\u0391-\uFFF5]+$
3、邮政编码
^[0-9]\d{5}$
4、QQ号码
^[1-9]\d{4,10}$
5、用户名(字母开头+数字/字母/下划线)
^[a-zA-Z][A-Za-z0-9_-]+$
6、手机号码
^1[3|4|5|8][0-9]\d{8}$
7、URL
^((http|https)://)?([\w-]+\.)+[\w+]+(/[\w-./?%&=]*)?$
8、18位身份证号
^(\d{6})(18|19|20)?(\d{2})([01]\d)([0123]\d)(\d{3})(\d|X|x)?$
四、使用实例
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
//要验证的字符串
String string = "http://www.runoob.com/java/java-regular-expressions.html";
//邮箱验证规则
String regEx = "[a-zA-Z_]{1,}[0-9]{0,}@(([a-zA-Z0-9]-*){1,}\\.){1,3}[a-zA-Z\\-]{1,}";
//在字符串中查询字符或字符串
String reg1 = "bike.*";
/*
* 常用正则表达式
*/
//一个或多个汉字
String chinese = "^[\u0391-\uFFF5]+$";
//邮政编码
String postNumber = "^[0-9]\\d{5}$";
//QQ号码
String QQNumber = "^[1-9]\\d{4,10}$";
//用户名(字母开头+数字/字母/下划线)
String userName = "^[a-zA-Z][A-Za-z0-9_-]+$";
//手机号码
String phoneNumber = "^1[3|4|5|8][0-9]\\d{8}$";
//URL
String url = "^((http|https)://)?([\\w-]+\\.)+[\\w+]+(/[\\w-./?%&=]*)?$";
//18位身份证号
String personId = "^(\\d{6})(18|19|20)?(\\d{2})([01]\\d)([0123]\\d)(\\d{3})(\\d|X|x)?$";
//编译正则表达式
Pattern pattern = Pattern.compile(url);
//忽略大小写的写法
Pattern pat = Pattern.compile(regEx, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(string);
//字符串是否与正则表达式相匹配
boolean rs = matcher.matches();
System.out.println(rs);
}
}