1、概念:描述了一种字符串匹配的模式(pattern),用来检查一个串是否含有某种子串、将匹配的子串替换、从某个串中取出符合某个条件的子串等。
2、作用:通常被用来检索、替换那些符合某个模式(规则)的文本。
3、用法:Java中正则表达式是由Pattern和Matcher类实现的。
Pattern类是用来表达和陈述所要搜索模式的对象,Matcher类是真正影响搜索的对象。
Pattern对象表示经编译的正则表达式。只要给Pattern的matcher( )方法送一个字符串就能获取一个Matcher对象。
//String对象成员matches方法
public boolean matches(String regex) {
return Pattern.matches(regex, this);
}
//Pattern的matches方法
public static boolean matches(String regex, Char Sequence input) {
Pattern p = Pattern.compile(regex);//compile将字符串编译成Pattern对象。
Matcher m = p.matcher(input);//获取一个matcher对象
return m.matches();
}
主要操作功能:匹配、切割、替换
匹配
匹配字符串:常见于匹配用户名注册
汉字:^[\u4e00-\u9fa5]{0,}$
英文和数字:^[A-Za-z0-9]+$ 或 ^[A-Za-z0-9]{4,40}$
由26个英文字母组成的字符串:^[A-Za-z]+$
由26个大写英文字母组成的字符串:^[A-Z]+$
由26个小写英文字母组成的字符串:^[a-z]+$
由数字和26个英文字母组成的字符串:^[A-Za-z0-9]+$
由数字、26个英文字母或者下划线组成的字符串:^\w+$ 或 ^\w{3,20}$
可以输入含有^%&',;=?$\"等字符:[^%&',;=?$\x22]+
特殊表达式:
Email地址:^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$
域名:[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(/.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+/.?
InternetURL:[a-zA-z]+://[^\s]* 或 ^https://([\w-]+\.)+[\w-]+(/[\w-./?%&=]*)?$
手机号码:^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$
国内电话号码:(0511-4405222、021-87888822):\d{3}-\d{8}|\d{4}-\d{7}
18位身份证:^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{4}$
密码(以字母开头,长度在6~18之间,只能包含字母、数字和下划线):^[a-zA-Z]\w{5,17}$
中文字符的正则表达式:[\u4e00-\u9fa5]
腾讯QQ号:[1-9][0-9]{4,} (腾讯QQ号从10000开始)
中国邮政编码:[1-9]\d{5}(?!\d) (中国邮政编码为6位数字)
IP地址:\d+\.\d+\.\d+\.\d+ (提取IP地址时有用)
替换:
string.replaceAll(String regex, String replacement):替换字符串
string.replaceFirst(String regex, String replacement):替换匹配的第一个字符串
eg:
package Lemon;
public class RegexDm {
public static void main(String[] args){
String s = "12342jasfkgnas234";
//把字符串里面的数字替换成*
String regex = "\\d";
String ss = "*";
String result = s.replaceAll(regex,ss);
System.out.println(result);
}
}
分割:将以正则表达式为界,将字符串分割成String数组
public String[] split(String regex)
eg:
public class exampl {
public static void main(String[] args) {
String commaStr = "123,456,789";
// 利用split方法指定按照逗号切割字符串
String[] commaArray = commaStr.split(",");
for (String item : commaArray) {
System.out.println(item);
}
}
}
ps:其实这些功能只是正则表达式的冰山一角,还有很多东西有待各位程序猿们继续探索!怀挺!