正则表达式
原理:用一些特定的符号来表示一些代码操作,学习正则表达式就是学习一些特殊符号的使用
作用:操作字符串
好处:简化对字符串的复杂操作
符号类
\\ //Java中表示反斜杠需要转义
\t //制表符 ('\u0009')
\n //换行符 ('\u000A')
\r //回车符 ('\u000D')
\f //换页符 ('\u000C')
字符类
[abc] //a、b、c中的其中一个
[^abc] //除a、b、c的其他字符(一个)
[a-zA-Z] //a到z或A到Z
预定义字符类
. //匹配任意一个字符
\d //数字:[0-9]
\D //非数字:[^0-9]
\s //空白字符:[\t\n\x0B\f\r]
\w //单词字符[a-zA-Z_0-9]
\W //非单词字符:[^\w]
边界匹配符
^ //行的开头
$ //行的结尾
\b //单词边界
数量词(X表示一个规则)
X? //0次或1次
X* //0次或多次
X+ //1次或多次
X{n} //n次
X{n,} //至少n次
X{n,m} //n到m次(取前不取后)
反义
\W //匹配任意不是字母、数字、下划线、汉字的字符
\S //匹配任意不是空白符的字符
\D //匹配任意非数字的字符
\B //匹配不是单词开头或结束的位置
[^x] //匹配除了x以外的任意字符
[^ab] //匹配除了ab字母以外的任意字符
逻辑运算符
XY //X后跟Y
X|Y //x或Y
(X) //捕获组
捕获组
括号内为一组,组默认编号从1开始,左括号从左往右计数:
((A)(B(C)))
1 ((A)(B(C)))
2 (A)
3 (B(C))
4 (C)
引用第一组:
(.)\\1 //表示叠词(.表示任意字符,\1表示第一组捕获组的结果,Java转义后为\\1)
\0表示整个字符串
匹配
使用String类的如下方法:
boolean matches(String regex) //"abc".matches("[a-z]{3}")
/**
匹配
*/
class RegexMatches
{
public static void main(String[] args)
{
//匹配QQ号码:首位不能为0,QQ号长度4-15位,全部是数字
matchesMethod("65465456", "[1-9]\\d{3,15}");
//匹配手机号码:13XXX 15XXX 18XXX,手机号11位
matchesMethod("1364545", "1[358]\\d{9}");
}
public static void matchesMethod(String str, String regex)
{
System.out.println(str.matches(regex));
}
}
分割
使用String类的如下方法:
String[] split(String regex) //"a.b.c".matches("\\.")
/**
分割
*/
class RegexSplit
{
public static void main(String[] args)
{
//" +"空格出现一次或多次
splitDemo("zhangsan lisi whangwu", " +");
//.在正则中匹配任意字符,正则中表示正常的点需转义"\.",其中的反斜杠在Java还需要转义"\\."
splitDemo("zhangsan.lisi.wangwu", "\\.");
//匹配\\的特例
splitDemo("c:\\abc\\a.txt", "\\\\");
//匹配叠词
splitDemo("asslfjjlskkdf", "(.)\\1");
}
public static void splitDemo(String str, String regex)
{
String[] arr = str.split(regex);
for(String s : arr)
{
System.out.println(s);
}
System.out.println("-----------------");
}
}
替换
使用String类的如下方法:
String replaceAll(String regex, String replacement) //"abbc".replaceAll("(.)\\1+", "$1")
/**
替换
*/
class regexReplaceAll
{
public static void main(String[] args)
{
//等于或超过5位的数字变问号
replaceAllDemo("sdlkfjlsdk1234234asdfsdf3234234234", "\\d{5,}", "?");
//替换中的特例,用$1来获取regex中的组1的字符
replaceAllDemo("abbbcddefggghijj", "(.)\\1+", "$1");
}
public static void replaceAllDemo(String str, String regex, String newStr)
{
str = str.replaceAll(regex, newStr);
System.out.println(str);
System.out.println("--------------------");
}
}
获取
import java.util.regex.*;
/**
获取
*/
class RegexMatcher
{
public static void main(String[] args)
{
String str = "ming tian fang jia le. tong xue men";
String regex = "[a-z]{4}";
//把正则封装为Pattern对象
Pattern p = Pattern.compile(regex);
//把正则和字符串匹配,返回匹配器Matcher
//String类中的matches和replaceAll方法内部均使用Matcher类中的方法(封装了Pattern和Matcher)
Matcher matcher = p.matcher(str);
//匹配字符串时会有一个指针,所以需要循环执行find方法,类似流中的read方法
while(matcher.find())
{
System.out.println(matcher.group());
}
}
}
---------------------- ASP.Net+Android+IOS开发</a>、 .Net培训、期待与您交流! ----------------------