正则表达式
转义字符
由于正则表达式也是字符串,再匹配正则中已经占用的符号时要进行转移,通常要使用两个反斜线,因为两个反斜线转移成一个反斜线,然后这个被转义后的反斜线再将后面要转义的符号转义
| 符号 |
匹配的字符 |
\\ |
\ |
\t |
\t |
\n |
\n |
特殊符号
[]中除拉&&、-、^其他就失去意义,无需转义,其中的关系是或的关系
| 符号 |
描述 |
|
. |
任意一个字符,除拉\r\n |
|
^ |
以开头,在[]中是取反 |
|
$ |
以结尾 |
|
[] |
单个符号范围 |
|
&& |
只作用于[]中,关系与取交 |
|
- |
只作用于[]中,表取值范围 |
|
{} |
数量词量词范围 |
|
() |
提升优先级和分组 |
|
| ` |
` |
关系或 |
数量词符号
贪婪模式(默认):重复次数多个满足条件情况下,尽可能的多匹配
非贪婪模式(数量词后跟一个?):重复次数多个满足情况下,尽可能的少匹配
| 符号 |
描述 |
* |
闭包,零次或多次 |
+ |
正闭包,一次或多次 |
? |
占位,零次或一次 |
{n} |
重复n次 |
{n,} |
重复n次或更多次 |
{n,m} |
重复n到m次 |
简化表达式
| 预定义类 |
描述 |
\d |
[0-9] |
\D |
[^0-9] |
\w |
[0-9a-zA-Z_] |
\W |
[^0-9a-zA-Z_] |
\s |
匹配空格(包括换行,制表空格)[\t\r\n\v\f] |
\S |
[^\t\r\n\v\f] |
字符串中的正则方法
| 方法名 |
描述 |
boolean matches(String regex) |
正则校验 |
String replaceAll(String regex, String replacement) |
正则全部替换 |
String replaceFirst(String regex, String replacement) |
正则首个替换 |
String[] split(String regex) |
正则全部拆分 |
String[] split(String regex, int limit) |
正则部分拆分 |
java爬虫
- 使用Pattern类的静态方法compile()进行编译正则,获得Pattern对象
- 使用Pattern的对象的matcher()方法获取匹配器
- 使用匹配器对匹配内容进行相应的操作
String str = "<a href=\"http://www.baidu.com\">百度</a>";
Pattern pattern = Pattern.compile("<a\\shref=\"(.*)\".*>.*</a>");
Matcher matcher = pattern.matcher(str);
while(matcher.find()){
System.out.println(matcher.group(0));
System.out.println(matcher.group(1));
System.out.println(matcher.group(1).replaceAll("http://",""));
}
Comments NOTHING