java.util.regex
正则在线检测 : 非常好用的工具,包括正则的解释以及结果的分析
正则表达式可用来搜索、处理字符串
一、Pattern
1、静态方法compile 创建Pattern对象
public static Pattern compile(String regex) {
return new Pattern(regex, 0);
}
2、pattern() 方法返回传入compile中的字符串
3、 静态方法matches 适用于只匹配一次,且匹配全部的字符串
public static boolean matches(String regex, CharSequence input) {
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(input);
return m.matches();
}
4、Creates a matcher that will match the given input against this pattern.
public Matcher matcher(CharSequence input) {
Matcher m = new Matcher(this, input);
return m;
}
二、Matcher
提供分组和多次匹配
1、find() 可以通过while 循环多次执行find方法
Attempts to find the next subsequence of the input sequence that matches the pattern.
public boolean find() {
synchronized (this) {
matchFound = findNextImpl(address, matchOffsets);
}
return matchFound;
}
2、group 返回匹配到子字符串,配合find使用,matches方法不做任何操作,返回原字符串
Returns the input subsequence matched by the previous match.
public String group() {
return group(0);
}
m.group() == m.group(0) == 所有匹配的字符(即匹配正则表达式整体结果)
group(1) 列出第一个括号匹配部分,group(2) 列出第二个括号匹配部分,group(3) 列出第三个括号匹配部分。
m.groups() 返回所有括号匹配的字符,以tuple格式。m.groups() == (m.group(0), m.group(1), …)