Java 正则表达式
正则表达式除了查看是否匹配之外, 还可以获取匹配的内容, 甚至修改, 替换匹配的内容.
Java 的正则表达式只有3个类, 都在 java.util.regex 包下面: Pattern, Matcher, 和 PatternSyntaxException.
- Pattern 是一个正则表达式的编译后表示, 只能通过它的 compile 静态方法获得;
- Matcher 就是一个执行正则表达式的引擎, 可以不断的查询, 检索输入的字符串. 它只能通过 pattern 的 matcher 方法获得;
- PatternSyntaxException 不同于一般的 exception, 它能提供更过与表达式匹配相关的错误信息;
字符类的例子
- [abc]................a, b, or c (simple class)
- [^abc]..............Any character except a, b, or c (negation)
- [a-zA-Z]...........a through z, or A through Z, inclusive (range)
- [a-d[m-p]]........a through d, or m through p: [a-dm-p] (union)
- [a-z&&[def]].....d, e, or f (intersection)
- [a-z&&[^bc]]....a through z, except for b and c: [ad-z] (subtraction)
- [a-z&&[^m-p]]..a through z, and not m through p: [a-lq-z]
预先定义的字符类:
- .------Any character (may or may not match line terminators)
- \d----A digit: [0-9]
- \D----A non-digit: [^0-9]
- \s----A whitespace character: [ \t\n\x0B\f\r]
- \S---A non-whitespace character: [^\s]
- \w---A word character: [a-zA-Z_0-9]
- \W---A non-word character: [^\w]
数量限定:
- X?.................once or not at all
- X*..................zero or more times
- X+.................one or more times
- X{n}...............exactly n times
- X{n,}..............at least n times
- X{n,m}...........at least n but not more than m times
要注意 0长度匹配 问题
边界匹配:
- ^...........The beginning of a line
- $...........The end of a line
- \b..........A word boundary
- \B..........A non-word boundary
- \A..........The beginning of the input
- \G..........The end of the previous match
- \Z..........The end of the input but for the final terminator, if any
- \z...........The end of the input
((A)(B(C))) 前面这个表达式有4 个分组.
Java 语言的正则表达式和 Perl 语言的最相近.
java.lang.String 的这4个方法都支持正则表达式: matches, split, replaceAll, replaceFirst. replace 方法不支持;
BackReference: 在后面要引用前面提到的分组:
在正则表达式中用 \ 后面跟数字, 代表引用表达式中第一个分组, 比如下面例子中的 \1 代表要再次出现前面的第一个一样的分组.
Pattern pattern2 = Pattern.compile("(\\d\\d)(\\w)\\1");
Matcher matcher2 = pattern2.matcher("12a12");
System.out.println(matcher2.find());
matcher2 = pattern2.matcher("12b13");
System.out.println(matcher2.find());
在 String 的 replaceAll replaceFirst 中可以使用 $后面跟数字代表正则表达式前面提到的分组, 下面例子中使用第1,3个分组替换原来
System.out.println("22:12".matches("(\\d\\d)(:)(\\d\\d)"));
System.out.println("22:12".replaceAll("(\\d\\d)(:)(\\d\\d)", "$1$3"));