正则表达式(regular expression)描述了一种字符串匹配的模式(pattern),可以用来检查一个串是否含有某种子串、将匹配的子串替换或者从某个串中取出符合某个条件的子串等。
字符 | 含义 |
---|---|
^ | 开始位置 |
$ | 结束位置 |
. | 单个任意字符(不一定包含换行符) |
\w | 单个"word"字符:字母/数字/下划线/汉字 |
\s | 单个空白字符(\n\r\t) |
\d | 单个数字字符 |
\b | 单词的开始或结束 |
字符 | 含义 |
---|---|
* | 0次或多次 |
+ | 1次或多次 |
? | 0次或1次 |
{n} | n次 |
{n,} | >=n次 |
{n,m} | n到m次 |
字符 | 含义 |
---|---|
[aeiou] | a/e/i/o/u字符的其中一个 |
[0-9] | 单个数字字符 |
[A-Z] | 单个大写字母 |
[A-Z0-9_] | 大写字母或数字或下划线之一 |
Hi | hi(或者[Hh]i) |
字符 | 含义 |
---|---|
[^aeiou] | 除a/e/i/o/u之外的一个字符 |
[^字符] | 非{字符}的一个字符 |
\W | 非\w的单个字符 |
\S | 非\s(空白) |
\D | 非\d |
\B | 非开头/结束位置 |
有的字符不可?,?法??个键来代表。
或者有的字符是特定的字符,需要转义才能使用原来的意思。
String的三个常用的方法:
public String[] split(String regex) {
return split(regex, 0);
}
public String replaceAll(String regex, String replacement) {
return Pattern.compile(regex).matcher(this).replaceAll(replacement);
}
public String replaceFirst(String regex, String replacement) {
return Pattern.compile(regex).matcher(this).replaceFirst(replacement);
}
public boolean matches(String regex) {
return Pattern.matches(regex, this);
}
Java中的正则表达式比较昂贵。
- 正则表达式需要解析
- 匹配过程是回溯
(?s) 代表可以匹配换行符
举个栗子:
原文:https://www.cnblogs.com/pipemm/p/12294768.html