字符 | 含义 | 代码示例 |
. | 任意一个字符,和.之前的字符无关 | String word = "a"; String regex = "."; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(word); print(m.matches());//true
String word = "a"; String regex = "a."; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(word); print(m.matches());//false
|
* | 0次或多次匹配之前的字符或者表达式 | String word = "ac"; String regex = "acc*"; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(word); print(m.matches()); //true
String word = "acb"; String regex = "acc*"; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(word); print(m.matches()); //false *只匹配c
|
+ | 一次或多次匹配之前的表达式或字符 | String word = "ac"; String regex = "acc+"; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(word); print(m.matches()); //false
String word = "accccc"; String regex = "acc+"; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(word); print(m.matches()); //true
|
{} | 用来限定之前的字符或表达式出现的次数 {n}表示正好出现n次 {n,}表示最少出现n次 {,m}表示最多出现m次 {n,m}表示出现n到m次 | String word = "acbb"; String regex = "acb{1}"; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(word); print(m.matches()); //true String word = "acbd"; String regex = "acb{1,}"; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(word); print(m.matches()); //false
|
? | 匹配一次之前的字符 | String word = "acbb"; String regex = "acb?"; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(word); print(m.matches()); //true
String word = "acbbb"; String regex = "acb?"; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(word); print(m.matches()); //false
|
[] | 匹配[]里的任一字符 | String word = "acbd"; String regex = "acb[abc]"; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(word); print(m.matches()); //false
String word = "acb"; String regex = "[abc]"; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(word); print(m.matches()); //false
String word = "acb"; String regex = "[abc]{1,}"; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(word); print(m.matches()); //true |
[^] | []取反 |
|
- | 限定一个范围,通常与[]连用 a-z表示所有字母 1-5表示匹配一到五数字 | String word = "123"; String regex = "[1-5]{1,}"; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(word); print(m.matches());//true |
\d | 表示数字 |
|
\D | \d取反 |
|
\s | 表示空白字符,包括空格,制表符,tab |
|
\S | \s取反 |
|
\w | 包括a-zA-Z1-9及_ |
|
\W | \w取反 |
|
^ | 表示字符开始 |
|
$ | 表示字符结束 |
|
示例程序:判断邮箱 String word = "238916@163.com"; String regex = "[\\w]{1,}@[\\w]{1,}\\.com$"; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(word); print(m.matches());
|
java中和正则表达式相关的类
- Pattern
定义一种模式,个人理解预编译正则表达式
- Matcher
对字符串的操作放在这里
- String
Matcher中的方法
find()查找,重复调用时,第一个不匹配内容之前的内容会被吃掉,所以第二次开始就不是从头查找了
lookingAt()从头查找
replaceAll()全部替换
appendReplacement()增强型替换
正则表达式表示正常的 \ 需要 \\\\