前言
看到了一篇非常不错的文章,忍不住转载学习一下,原文地址:
Java正则表达式教程
引言
什么是正则表达式?
正则表达式(regular expressions)是一种描述字符串集的方法,它是以字符串集中各字符串的共有特征为依据的。正则表达式可以用于搜索、编辑或者是操作文本和数据。它超出了java程序设计语言的标准语法,因此有必要去学习特定的语法来构建正则表达式。正则表达式的变化是复杂的,一旦你理解了它们是如何被构造的话,你就能解析或者构建任意的正则表达式了。本教程讲授java.util.regex API 所支持的正则表达式语法,以及介绍几个可运行的例子来说明不同的对象间是如何交互的。
java.util.regex包是如何描述正则表达式的?
java.util.regex包由三个类组成:Pattern、Matcher和PatternSyntaxException
- Pattern对象表示一个已编译的正则表达式。Pattern类没有提供公共的构造方法。要构建一个模式,首先必须调用公共的静态compile方法,它将返回一个Pattern对象。这个方法接受正则表达式作为第一个参数。本教程的开始部门将教你必须的语法。
- Matcher是一个靠着输入的字符串来解析这个模式和完成匹配操作的对象。
- PatternSyntaxException对象是一个未检查异常,指示了正则表达式的一个语法错误。
本教程的最后几章课程会详细地说明各个类。首当其冲的问题是:必须理解正则表达式是如何被构建的,因此下一节引入了一个简单的测试工具,重复地用于探究它们的语法
测试工具
这节给出了一个可重用的测试用具 RegexTestHarness.java,用于探究构建API所支持的正则表达式。源码如下:
package regex;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexTestHarness {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
while (true) {
System.out.printf("Enter your regex: ");
Pattern pattern = Pattern.compile(scanner.nextLine());
System.out.printf("Enter input string to search: ");
Matcher matcher = pattern.matcher(scanner.nextLine());
boolean found = false;
while (matcher.find()) {
System.out
.printf("I found the text \"%s\" starting at index %d and ending at index %d.\n",
matcher.group(), matcher.start(), matcher.end());
found = true;
}
if (!found) {
System.out.println("No match found!\n");
}
}
} catch (Exception e) {
scanner.close();
}
}
}
使用:
java RegexTestHarness
这个命令来运行,没有被接受的命令行参数,这个应用会不停的循环执行下去,提示用户输入正则表达式和字符串。虽然说使用这个测试工具是可选的,但你会发现它用于探究下文所讨论的测试用例将更为方便(ps:但是我更推荐用这个online的工具,地址:
http://www.regexplanet.com/)
字符串
在大多数的情况下,API所支持模式匹配的基本形式是匹配字符串,如果正则表达式是foo,输入的字符串也是foo,这个匹配将会是成功的,因为这两个字符串是相同的。试着用测试工具来测试一下:
Enter your regex: foo
Enter input string to search: foo
I found the text "foo" starting at index 0 and ending at index 3.
结果确实是成功的。注意当输入的字符串是3个字符串长度的时候,开始的索引是0,结束的索引是3。这个是约定俗称的,范围包括开始的索引,不包括结束的索引,如下图所示:
字符串中的每一个字符位于其自身的单元格(cell)中,在每个单元格之间有索引指示位。字符串“foo”始于索引0处,止于索引3处,即使是这些字符它们自己仅占据了0、1和2号单元格。就子序列匹配而言,你会注意到一些重叠,下一次匹配开始索引与前一次匹配的结束索引是相同的:
Enter your regex: foo
Enter input string to search: foofoofoo
I found the text "foo" starting at index 0 and ending at index 3.
I found the text "foo" starting at index 3 and ending at index 6.
I found the text "foo" starting at index 6 and ending at index 9.
元字符
API也支持许多可以影响模式匹配的特殊字符。把正则表达式改为cat,并输入字符串“cats”,输出如下所示:
Enter your regex: cat.
Enter input string to search: cats
I found the text "cats" starting at index 0 and ending at index 4.
虽然在输入的字符串中没有点(.),但这个匹配仍然是成功的。这是由于(.)是一个元字符(metacharacters)。这个例子为什么能匹配成功的原因在于,元字符(.)指的是“任意字符”。
API所支持的元字符有:( [ { \ ^ - $ | } ] ) ? * + .
有两种不同的元字符:一种是可以在模式中方括号外任何地方使用的,另一种是需要在方括号内使用的。
在方括号外使用的元字符如下:
- \:一般用于转义字符
- ^:断言目标的开始位置(或在多行模式下是行首)
- $:断言目标的结束位置(或在多行模式下是行尾)
- .:匹配除含行符外的任何字符
- [:开始字符类的定义
- ]:结束字符类的定义
- (:子组的开始标记
- ):子组的结束标记
- ?:作为量词,表示0次或1次匹配
- *:量词,0次或多次匹配
- +:量词,1次或多次匹配
- {:自定义量词开始标记
- }:自定义量词结束标记
在方括号内的部分称为“字符类”:
- \:转义字符
- ^:仅在作为第一个字符(方括号内)时,表明字符取反
- -:标记字符范围
有两种方法可以强制将元字符处理成为普通字符:
- 在元字符前加上反斜线(\)
- 把它放在\Q(引用开始)和\E(引用结束)之间
字符类
如果你曾看过Pattern类的说明,会看到一些构建正则表达式的该数。在这一节中你会发现下面的一些表达式:
左边列指定正则表达式的构造,右边列描述每个构造的匹配的条件。注意:“字符类(character class)”这个词中的“类(class)”指的并不是一个.class文件。在正则表达式的语义中,字符类是放在方括号里的字符集,指定了一些字符中的一个能被给定字符串所匹配。
简单类(Simple Classes)
字符类最基本的格式是把一些字符放在一对方括号内。例如:正则表达式[bcr]at会匹配“bat”、“cat”或者“rat”,这是由于其定义了一个字符类(接受“b”,“c”或者“r”中的一个字符)作为它的首字符。
Enter your regex: [bcr]at
Enter input string to search: bat
I found the text "bat" starting at index 0 and ending at index 3.
Enter your regex: [bcr]at
Enter input string to search: cat
I found the text "cat" starting at index 0 and ending at index 3.
Enter your regex: [bcr]at
Enter input string to search: rat
I found the text "rat" starting at index 0 and ending at index 3.
在上面的例子中,在第一个字符匹配字符类中所定义字符中的一个时,整个匹配就成功的。
否定
要匹配除那些列表之外所有的字符时,可以在字符类的开始处加上^元字符,这种就被称为否定(negation)
Enter your regex: [^bcr]at
Enter input string to search: bat
No match found!
Enter your regex: [^bcr]at
Enter input string to search: cat
No match found!
Enter your regex: [^bcr]at
Enter input string to search: rat
No match found!
Enter your regex: [^bcr]at
Enter input string to search: hat
I found the text "hat" starting at index 0 and ending at index 3.
在输入的字符串中第一个字符不包含在字符类中所定义字符中的一个时,匹配是成功的。
范围
有时会想到定义一个包含值范围的字符类,诸如,“a到h“的字母或者是”1到5”的数字。指定一个范围,只要在被匹配的首字符和末字符之间插入“-”字符,比如[1-5]或者[a-h]。也可以在类里每个的边上放置不同的范围来提高匹配的可能性,例如[a-zA-Z]将会匹配a到z(小写字母)或者A到Z(大写字母)中的任何一个字符。
下面是一些范围和否定的例子:
Enter your regex: [a-c]
Enter input string to search: a
I found the text "a" starting at index 0 and ending at index 1.
Enter your regex: [a-c]
Enter input string to search: b
I found the text "b" starting at index 0 and ending at index 1.
Enter your regex: [a-c]
Enter input string to search: d
No match found!
Enter your regex: foo[^1-5]
Enter input string to search: foo1
No match found!
Enter your regex: foo[^1-5]
Enter input string to search: foo6
I found the text "foo6" starting at index 0 and ending at index 4.
并集
可以使用并集(union)来建一个由两个或者两个以上字符类所组成的单字符类。要构建一个并集,只要在一个字符类的边上嵌套另外一个,比如:[0-4[6-8]],这种奇怪的方式构建的并集字符类,可以匹配 0,1,2,3,4,6,7,8这几个数字。
Enter your regex: [0-4[6-8]]
Enter input string to search: 0
I found the text "0" starting at index 0 and ending at index 1.
Enter your regex: [0-4[6-8]]
Enter input string to search: 5
No match found!
交集
建一个仅仅匹配自身嵌套类中公共部分字符的字符类时,可以像[0-9&&[345]]那样使用&&。这种方式构建出来的交集(intersection)简单字符类,仅仅以匹配两个字符类中的3,4,5共有部分。
Enter your regex: [2-8&&[3-9]]
Enter input string to search: 6
I found the text "6" starting at index 0 and ending at index 1.
Enter your regex: [2-8&&[3-9]]
Enter input string to search: 2
No match found!
Enter your regex: [2-8&&[3-9]]
Enter input string to search: 9
No match found!
差集
最后,可以使用差集(subtraction)来否定一个或多个嵌套的字符类,比如:[0-9&&[^345]],这个是构建一个匹配除3,4,5之外所有0到9数字的简单字符类。
Enter your regex: [0-9&&[^345]]
Enter input string to search: 6
I found the text "6" starting at index 0 and ending at index 1.
Enter your regex: [0-9&&[^345]]
Enter input string to search: 3
No match found!
Enter your regex: [0-9&&[^345]]
Enter input string to search: 5
No match found!
到此为止,已经涵盖了如何建立字符类的部门。在继续下一节之前,可以试着回想那张字符类表。
预定义字符类
Pattern的API包有许多有用的预定义字符类(predefined character classes),提供了常用的正则表达式的简写形式
上表中,左列是构造右列字符类的简写形式。例如:\d指定是数字范围(0-9),\w指的是单词字符([a-zA-Z0-9_])。无论何时都有可能使用预定义字符类,它可以使代码更易阅读,更易从难看的字符类中排除错误。以反斜线(\)开始的构造称为转义构造(escaped constructs)。在字符串中使用转义构造,必须在一个反斜线前再增加一个反斜线用于字符串的编译,例如:
private final String REGEX = "\\d"; // 单个数字
这个例子中\d是正则表达式,另外的那个反斜线是用于代码编译所必须的。但是测试用具读取的表达式,是直接从控制台输入的,因此不需要那个多出来的反斜线
下面的例子说明了预定义字符类的用法:
Enter your regex: .
Enter input string to search: 0
I found the text "0" starting at index 0 and ending at index 1.
Enter your regex: .
Enter input string to search: a
I found the text "a" starting at index 0 and ending at index 1.
Enter your regex: \d
Enter input string to search: 1
I found the text "1" starting at index 0 and ending at index 1.
Enter your regex: \d
Enter input string to search: a
No match found!
Enter your regex: \D
Enter input string to search: a
I found the text "a" starting at index 0 and ending at index 1.
Enter your regex: \D
Enter input string to search: 1
No match found!
Enter your regex: \s
Enter input string to search:
I found the text " " starting at index 0 and ending at index 1.
Enter your regex: \s
Enter input string to search:
No match found!
Enter your regex: \S
Enter input string to search: a
I found the text "a" starting at index 0 and ending at index 1.
Enter your regex: \w
Enter input string to search: a
I found the text "a" starting at index 0 and ending at index 1.
Enter your regex: \w
Enter input string to search: 1
I found the text "1" starting at index 0 and ending at index 1.
Enter your regex: \W
Enter input string to search: a
No match found!
Enter your regex: \W
Enter input string to search: -
I found the text "-" starting at index 0 and ending at index 1.
量词
这一节我们来看一下贪婪(greedy)、勉强(reluctant)和侵占(possessive)量词,来匹配指定表达式X的次数。
量词(quantifiers)允许指定匹配出现的次数,方便起见,当前Pattern API规范下,描述了贪婪、勉强和侵占三种量词。首先粗略的看一下,量词X?、X??和X?+都允许匹配X零次或一次,精确的做同样的事情,但它们之间有细微的不同之处,在这节结束前会进行说明。
那我们现在就从贪婪量词开始,构建三个不同的正则表达式:字符a后面跟着?、*和+。接下来看一下,这些表达式来测试输入的字符串是空字符串时会发生什么:
Enter your regex: a?
Enter input string to search:
I found the text "" starting at index 0 and ending at index 0.
Enter your regex: a*
Enter input string to search:
I found the text "" starting at index 0 and ending at index 0.
Enter your regex: a+
Enter input string to search:
No match found!
零长度匹配
在上面的例子中,开始的两个匹配是成功的,这是因为表达式a?和a*都允许字符出现零次。就目前而言,这个例子不像其他的,也许你注意到了开始和结束的索引都是0.输入的空字符串没有长度,因此该测试简单地在索引0上匹配什么都没有,诸如此类的匹配称为零长度匹配(zero-length matches)。零长度匹配会出现在以下几种情况:输入空的字符串、在输入字符串的开始处、在输入字符串最后字符的后面,或者是输入字符串任意两个字符之间。由于它们开始和结束的位置有着相同的索引,因此零长度匹配是容易被发现的。
我们来看一下关于零长度匹配更多的例子。把输入的字符串改为单个字符“a”,你会注意到一些有意思的事情:
Enter your regex: a?
Enter input string to search: a
I found the text "a" starting at index 0 and ending at index 1.
I found the text "" starting at index 1 and ending at index 1.
Enter your regex: a*
Enter input string to search: a
I found the text "a" starting at index 0 and ending at index 1.
I found the text "" starting at index 1 and ending at index 1.
Enter your regex: a+
Enter input string to search: a
I found the text "a" starting at index 0 and ending at index 1.
所有的三个量词都是用来寻找字母“a”的,但是前面两个在索引1处找到了零长度匹配,也就是说,在输入字符串最后一个字符的后面。回想一下,匹配把字符“a”看作索引0和1之间的单元格,并且测试用具一致循环下去直到不再有匹配为止。依赖于所使用的量词不同,最后字符后面的索引“什么都没有”的存在可以或者不可以触发一个匹配
现在把输入的字符串改为一行5个“a”时,会得到下面的结果:
Enter your regex: a?
Enter input string to search: aaaaa
I found the text "a" starting at index 0 and ending at index 1.
I found the text "a" starting at index 1 and ending at index 2.
I found the text "a" starting at index 2 and ending at index 3.
I found the text "a" starting at index 3 and ending at index 4.
I found the text "a" starting at index 4 and ending at index 5.
I found the text "" starting at index 5 and ending at index 5.
Enter your regex: a*
Enter input string to search: aaaaa
I found the text "aaaaa" starting at index 0 and ending at index 5.
I found the text "" starting at index 5 and ending at index 5.
Enter your regex: a+
Enter input string to search: aaaaa
I found the text "aaaaa" starting at index 0 and ending at index 5.
在“a”出现零次或一次时,表达式a?寻找到所匹配的每一个字符。表达式a*找到了两个单独的匹配:第一次匹配到所有的字母“a”,然后匹配到最后一个字符后面的索引。最后,a+匹配了所有出现的字母“a”,忽略了最后索引出“什么都没有”的存在
在这里,你也许会感到疑惑,开始的两个量词在遇到除了“a”的字母时会有什么结果。例如,在“ababaaaab”中遇到了字母“b”会发生什么呢?
下面我们来看一下:
Enter your regex: a?
Enter input string to search: ababaaaab
I found the text "a" starting at index 0 and ending at index 1.
I found the text "" starting at index 1 and ending at index 1.
I found the text "a" starting at index 2 and ending at index 3.
I found the text "" starting at index 3 and ending at index 3.
I found the text "a" starting at index 4 and ending at index 5.
I found the text "a" starting at index 5 and ending at index 6.
I found the text "a" starting at index 6 and ending at index 7.
I found the text "a" starting at index 7 and ending at index 8.
I found the text "" starting at index 8 and ending at index 8.
I found the text "" starting at index 9 and ending at index 9.
Enter your regex: a*
Enter input string to search: ababaaaab
I found the text "a" starting at index 0 and ending at index 1.
I found the text "" starting at index 1 and ending at index 1.
I found the text "a" starting at index 2 and ending at index 3.
I found the text "" starting at index 3 and ending at index 3.
I found the text "aaaa" starting at index 4 and ending at index 8.
I found the text "" starting at index 8 and ending at index 8.
I found the text "" starting at index 9 and ending at index 9.
Enter your regex: a+
Enter input string to search: ababaaaab
I found the text "a" starting at index 0 and ending at index 1.
I found the text "a" starting at index 2 and ending at index 3.
I found the text "aaaa" starting at index 4 and ending at index 8.
即使字母“b”在单元格1、3、8中出现,但在这些位置上的输出报告了零长度匹配。正则表达式a?不是特意地去寻找字母“b”,它仅仅是去找字母“a”存在或者其中缺少的。如果量词允许匹配“a”零次,任何输入的字符不是“a”时将会作为零长度匹配。在前面的例子中,根据讨论的规则保证了a被匹配。
对于要精确的匹配一个模式n次时,可以简单地在一对花括号内指定一个数值:
Enter your regex: a{3}
Enter input string to search: aa
No match found!
Enter your regex: a{3}
Enter input string to search: aaa
I found the text "aaa" starting at index 0 and ending at index 3.
Enter your regex: a{3}
Enter input string to search: aaaa
I found the text "aaa" starting at index 0 and ending at index 3.
这里,正则表达式a{3}在一行中寻找连续出现三次的字母“a”。第一次测试失败的原因在于,输入的字符串没有足够的a用来匹配;第二次测试输出的字符串正好包括了三个“a”,触发了一次匹配;第三次测试也触发了一次匹配,这是由于在输出的字符串的开始部分正好有三个“a”。接下来的事情与第一次的匹配是不相关的,如果这个模式将在这一点后续出现,那它将会触发接下来的匹配:
Enter your regex: a{3}
Enter input string to search: aaaaaaaaaa
I found the text "aaa" starting at index 0 and ending at index 3.
I found the text "aaa" starting at index 3 and ending at index 6.
I found the text "aaa" starting at index 6 and ending at index 9.
对于需要一个模式出现至少n次时,可以在这个数字后面加上一个逗号(,);
Enter your regex: a{3,}
Enter input string to search: aaaaaaaa
I found the text "aaaaaaaa" starting at index 0 and ending at index 8.
捕获组和字符类中的量词
到目前为止,仅仅测试了输入的字符串包括一个字符的量词。实际上,量词仅仅可能附在一个字符后面一次,因此正则表达式abc+的意思就是“a后面接着b,再接着一次或者多次的c”,它的意思并不是指abc一次或者多次。然而,量词也可能附在字符类和捕获组的后面,比如,[abc]+表示一次或者多次的a或b或c,(abc)+表示一次或者多次的“abc”组。
我们来指定(dog)组在一行中三次进行说明
Enter your regex: (dog){3}
Enter input string to search: dogdogdogdogdogdog
I found the text "dogdogdog" starting at index 0 and ending at index 9.
I found the text "dogdogdog" starting at index 9 and ending at index 18.
Enter your regex: dog{3}
Enter input string to search: dogdogdogdogdogdog
No match found!
上面的第一个例子找到了三个匹配,这是由于量词用在了整个捕获组上。然而,把圆括号去掉,这时的量词{3}现在仅用在了字母“g”上,从而导致了这个匹配的失败。
类似地,也能把量词应用于整个字符类:
Enter your regex: [abc]{3}
Enter input string to search: abccabaaaccbbbc
I found the text "abc" starting at index 0 and ending at index 3.
I found the text "cab" starting at index 3 and ending at index 6.
I found the text "aaa" starting at index 6 and ending at index 9.
I found the text "ccb" starting at index 9 and ending at index 12.
I found the text "bbc" starting at index 12 and ending at index 15.
Enter your regex: abc{3}
Enter input string to search: abccabaaaccbbbc
No match found!
上面的第一个例子中,量词{3}应用在了整个字符类上,但是第二个例子这个量词仅仅用在字母“c”上。
贪婪、勉强和侵占量词间的不同
在贪婪、勉强和侵占三个量词间有着细微的不同。
贪婪量词之所以称之为“贪婪的”,这是由于它们强迫匹配器读入(或者称之为吃掉)整个输入的字符串,来优先尝试第一次匹配,如果第一次尝试匹配(对于整个输入的字符串)失败,匹配器会通过回退整个字符串的一个字符再一次进行尝试,不断地进行处理直到找到一个匹配,或者左边没有更多的字符来用于回退了。赖于表达式中使用的量词,最终它将尝试地靠着1或0个字符的匹配。
但是,勉强量词采用相反的途径:从输入字符串的开始处开始,因此每次勉强地吞噬一个字符来寻找匹配,最终它们会尝试整个输出的字符串。
最后,侵占量词始终是吞掉整个输入的字符串,尝试着一次(仅有一次)匹配。不像贪婪量词那样,侵占量词绝不会回退,即使这样是允许全部的匹配成功
为了说明一下,看看输入的字符串是 xfooxxxxxxfoo 时 :
Enter your regex: .*foo
Enter input string to search: xfooxxxxxxfoo
I found the text "xfooxxxxxxfoo" starting at index 0 and ending at index 13.
Enter your regex: .*?foo
Enter input string to search: xfooxxxxxxfoo
I found the text "xfoo" starting at index 0 and ending at index 4.
I found the text "xxxxxxfoo" starting at index 4 and ending at index 13.
Enter your regex: .*+foo
Enter input string to search: xfooxxxxxxfoo
No match found!
第一个例子使用贪婪量词 .* ,寻找紧跟着字母"foo "任何东西零次或者多次。由于量词是贪婪匹配的,表达式的.*部分第一次吃掉整个输入的字符串。在这一点,全部表达式不能成功的进行匹配,这是由于最后三个字母(f o o)已经被消耗掉了。那么匹配器会慢慢地每次回退一个字母,直到返回的“foo ”在最右边出现,这时匹配成功并且搜索终止
然而,第二个例子采用勉强量词,因此通过首次消耗什么也没有作为开始。由于foo并没有出现在字符串的开始,它被强迫吞掉第一个字母(“x”),在 0 和 4 处触发了第一个匹配。测试用具会继续处理,直到输入的字符串耗尽为止。在 4 和 13 找到了另外一个匹配
第三个例子的量词是侵占的,所以在寻找匹配时失败了。在这种情况下,整个输入的字符串被.*+消耗了,什么都没有生下来满足表达式末尾的“foo
”
捕获组
在上一节中,学习了每次如何把量词放在一个字符、字符类或者捕获组中。到目前为止,还没有详细讨论捕获组的概念
捕获组(capturing group)是将多个字符作为单独的单元来对待的一种方式。构建它们可以通过把字符放在一对圆括号中而成为一组。例如,正则表达式(dog)建了单个的组,包括字符“d”、“o”和“g”。匹配捕获组输入的字符串部门将会存放于内存中,稍后通过反向引用再次调用
编号方式
在Pattern的API描述中,捕获组通过从左至右计算开始的圆括号进行编号。例如,在表达式 ((A)(B(C)))中,有下面的四组:
- ((A)(B(C)))
- (A)
- (B(C))
- (C)
要找出当前的表达式中有多少组,通过调用Matcher对象的groupCount方法。groupCount方法返回int类型值,表示当前Matcher模式中捕获组的数量。例如,groupCount返回4时,表示模式中包含有4个捕获组
有一个特别的组--组0,它表示整个表达式。这个组不包括在groupCount的报告范围内
Matcher的一些方法,可以指定int类型的特定组号作为参数,因此理解组是如何编号的是尤为重要的
public int start(int group) :返回之前的匹配操作期间,给定组所捕获的子序列的初始索引
public int end(int group):返回之前的匹配操作期间,给定组所捕获子序列的最后字符索引加1
public String group(int group):返回之前的匹配操作期间,通过给定组而捕获的输入子序列
反向引用
匹配输入字符串的捕获组部分会存放在内存中,通过反向引用(backreferences)稍后再调用。在正则表达式中,反向引用使用反斜线(\)后跟一个表示需要再调用组号的数字来表示。例如,表达式(\d\d)定义了匹配一行中的两个数字的捕获组,通过反向引用\1,表达式稍候会被再次的调用
匹配两个数字,且后面跟着两个完全相同的数字时,就可以使用(\d\d)\1作为正则表达式:
Enter your regex: (\d\d)\1
Enter input string to search: 1212
I found the text "1212" starting at index 0 and ending at index 4.
Enter your regex: (\d\d)\1
Enter input string to search: 121212
I found the text "1212" starting at index 0 and ending at index 4.
如果更改最后的两个数字,这时匹配就会失败:
Enter your regex: (\d\d)\1
Enter input string to search: 121212
I found the text "1212" starting at index 0 and ending at index 4.
Enter your regex: (\d\d)\1
Enter input string to search: 1234
No match found!
边界匹配器
就目前而言,我们的兴趣在于指定输入字符串中某些位置是否有匹配,还没有考虑到字符串的匹配产生在什么地方
通过指定一些边界匹配器(boundary matchers)的信息,可以是模式匹配更为精确。比如说你对某个特定的单词感兴趣,并且它只出现在行首或者是行尾。又或者你想知道匹配发生在单词边界(word boundary),或者是上一个匹配的尾部
下表列出了所有的边界匹配器及其说明:
接下来的例子中,说明了^和$边界匹配器的用法。注意上表中,^匹配行首,$匹配行尾
Enter your regex: ^dog$
Enter input string to search: dog
I found the text "dog" starting at index 0 and ending at index 3.
Enter your regex: ^dog$
Enter input string to search: dog
No match found!
Enter your regex: ^dog\w*
Enter input string to search: dogblahblah
I found the text "dogblahblah" starting at index 0 and ending at index 11.
第一个例子的匹配是成功的,这是因为模式占据了整个输入的字符串。第二个例子失败了,是由于输入的字符串在开始部分包含了额外的空格。第三个例子,需要dog放在行首,后面跟的是不限数量的单词字符
对于检查一个单词开始和结束的边界模式(用于长字符串里子字符串),这时可以在两边使用\b,例如\bdog\b
Enter your regex: \bdog\b
Enter input string to search: The dog plays in the yard.
I found the text "dog" starting at index 4 and ending at index 7.
Pattern类的方法
到目前为止,仅使用测试用具来建立最基本的Pattern对象。在这一节中,我们将探讨一些诸如使用标志构建模式、使用内嵌标志表达式等高级的技术。同时也探讨了一些目前还没有讨论过的其他有用的方法
使用标志构建模式
Pattern类定义了备份的compile方法,用于接受影响模式匹配方式的标志集。标志参数是一个位掩码,可以是下面公共静态字段中的任意一个:
Pattern.CANON_EQ
启用规范等价。在指定此标志后,当且仅当在其完整的规范分解匹配时,两个字符被视为匹配。例如,表达式a\u030A[8]在指定此标志后,将匹配字符串“\u00E5”(即字符 å)。默认情况下,匹配不会采用规范等价。指定此标志可能会对性能会有一定的影响
启用规范等价。在指定此标志后,当且仅当在其完整的规范分解匹配时,两个字符被视为匹配。例如,表达式a\u030A[8]在指定此标志后,将匹配字符串“\u00E5”(即字符 å)。默认情况下,匹配不会采用规范等价。指定此标志可能会对性能会有一定的影响
Pattern.CASE_INSENSITIVE
启用不区分大小写匹配。默认情况下,仅匹配 US-ASCII 字符集中的字符。Unicode 感知(Unicode-aware)的不区分大小写匹配,可以通过指定 UNICODE_CASE 标志连同此标志来启用。不区分大小写匹配也能通过内嵌标志表达式(?i)来启用。指定此标志可能会对性能会有一定的影响
Pattern.COMMENTS
模式中允许存在空白和注释。在这种模式下,空白和以#开始的直到行尾的内嵌注释会被忽略。注释模式也能通过内嵌标志表达式(?x)来启用
Pattern.DOTALL
启用 dotall 模式。在 dotall 模式下,表达式.匹配包括行结束符在内的任意字符。默认情况下,表达式不会匹配行结束符。dotall 模式也通过内嵌标志表达式(?x)来启用。[s 是“单行(single-line)”模式的助记符,与 Perl 中的相同
Pattern.LITERAL
启用模式的字面分析。指定该标志后,指定模式的输入字符串作为字面上的字符序列来对待。输入序列中的元字符和转义字符不具有特殊的意义了。CASE_INSENSITIVE 和 UNICODE_CASE 与此标志一起使用时,会对匹配产生一定的影响。其他的标志就变得多余了。启用字面分析没有内嵌标志表达式
Pattern.MULTILINE
启用多行(multiline)模式。在多行模式下,表达式^和$分别匹配输入序列行结束符前面和行结束符的前面。默认情况下,表达式仅匹配整个输入序列的开始和结尾。多行模式也能通过内嵌标志表达式(?m)来启用
Pattern.UNICODE_CASE
启用可折叠感知 Unicode(Unicode-aware case folding)大小写。在指定此标志后,需要通过 CASE_INSENSITIVE 标志来启用,不区分大小写区配将在 Unicode 标准的意义上来完成。默认情况下,不区分大小写匹配仅匹配 US-ASCII 字符集中的字符。可折叠感知 Unicode 大小写也能通过内嵌标志表达式(?u)来启用。指定此标志可能会对性能会有一定的影响
Pattern.UNIX_LINES
启用 Unix 行模式。在这种模式下,.、^和$的行为仅识别“\n”的行结束符。Unix 行模式可以通过内嵌标志表达式(?d)来启用
启用 Unix 行模式。在这种模式下,.、^和$的行为仅识别“\n”的行结束符。Unix 行模式可以通过内嵌标志表达式(?d)来启用
接下来,将修改测试用具RegexTestHarness.java,用于构建不区分大小写匹配的模式
首先,修改代码去掉用complie的另外一个备用的方法:
Pattern pattern = Pattern.compile(scanner.nextLine(), Pattern.CASE_INSENSITIVE);
编译并运行这个测试用具,会得出下面的结果:
Enter your regex: dog
Enter input string to search: DoGDOg
I found the text "DoG" starting at index 0 and ending at index 3.
I found the text "DOg" starting at index 3 and ending at index 6.
正如你所看到的,不管是否大小写,字符串字面上是“dog”的都产生了匹配。使用多个标志来编译一个模式,使用按位或操作符"|"分隔各个标志。为了更清晰地说明,下面的示例代码使用硬编码(hardcode)的方式,来取代控制台中的读取:
内嵌标志表达式
使用内嵌标志表达式(embedded flag expressions)也可以启用不同的标志。对于两个参数的compile方法,内嵌标志表达式是可选的,因为它在自身的正则表达式中被指定了。下面的例子使用最初的测试用具,使用内嵌标志表达式(?i)来表示启用不区分大小写的匹配
Enter your regex: (?i)foo
Enter input string to search: FOOfooFOofoO
I found the text "FOO" starting at index 0 and ending at index 3.
I found the text "foo" starting at index 3 and ending at index 6.
I found the text "FOo" starting at index 6 and ending at index 9.
I found the text "foO" starting at index 9 and ending at index 12.
所有匹配无关大小写都一次次地成功了
内嵌标志表达式所对应Pattern的公用的访问字段表示如下表:
使用matches(String,CharSequence)方法
Pattren类定义了一个方便的matches方法,用于快速的检查模式是否表示给定的字符串。与使用所有的公共静态方法一样,应该通过它的类名来调用matches方法,诸如:
Pattren.matches("\\d", "1");
这个例子中,方法返回true,这是由于数组“1”匹配了正则表达式\d
使用split(String)方法
split方法是一个重要的工具,用于收集依赖于被匹配的模式任一边的文本。如下面的代码所示,split方法能从“one:two:three:four:five”字符串中解析出“one two three four five”单词:
import java.util.regex.Pattern;
public class SplitDemo {
private static final String REGEX = ":";
private static final String INPUT = "one:two:three:four:five";
public static void main(String[] args) {
Pattern pattren = Pattern.compile(REGEX);
String[] items = pattren.split(INPUT);
for(String s : items) {
System.out.println(s);
}
}
}
输出:
one
two
three
four
five
简而言之,已经使用冒号(:)取代了复杂的正则表达式匹配字符串文字。以后仍会使用Pattern和Matcher对象,也能使用split得到位于任意正则表达式各边的文本。下面的代码是一样的例子,使用数字作为split的参数:
import java.util.regex.Pattern;
public class SplitDemo2 {
private static final String REGEX = "\\d";
private static final String INPUT = "one9two4three7four1five";
public static void main(String[] args) {
Pattern pattren = Pattern.compile(REGEX);
String[] items = pattren.split(INPUT);
for (String s : items) {
System.out.println(s);
}
}
}
输出:
one
two
three
four
five
其他有用的方法
你可以从下面的方法中找到比较好用的方法:
public static String quote(String s):返回指定字符串字面模式的字符串。此方法会产生一个字符串,能被用于构建一个与字符串s匹配的Pattren,好像它是一个字面上的模式。输入序列中的元字符和转义字符序列将没有特殊的意义了
public String toString():返回这个模式的字符串表现形式。这是一个编译过的模式中的正则表达式
在java.lang.String中等价的Pattern方法
java.lang.String通过模拟java.util.regex.Pattren行为的几个方法,也可以支持正则表达式。方便起见,下面主要摘录了出现在API关键的方法
public boolean matches(String regex):告知字符串是否匹配给定的正则表达式。调用 str.matches(regex)方法所产生的结果与作为表达式的 Pattern.matches(regex, str)的结果是完全一致
public String[] split(String regex, int limit):依照匹配给定的正则表达式来拆分字符串。调用 str.split(regex, n)方法所产生的结果与作为表达式的 Pattern.compile(regex).split(str, n) 的结果完全一致
public String[] split(String regex):依照匹配给定的正则表达式来拆分字符串。这个方法与调用两个参数的 split 方法是相同的,第一个参数使用给定的表达式,第二个参数限制为 0。在结果数组中不包括尾部的空字符串
public String replace(CharSequence target,CharSequence replacement):将字符串中每一个匹配替换匹配字面目标序列的子字符串,替换成指定的字面替换序列。这个替换从字符串的开始处理直至结束,例如,把字符串“aaa”中的“aa”替换成“b”,结果是“ba”,而不是“ab”。
Matcher类的方法
在这一节中来看看Matcher类中其他一些有用的方法。方便起见,下面列出的方法是按照功能来分组的
索引方法
索引方法(index methods)提供了一些正好在输入字符串中发现匹配的索引值:
public int start():返回之前匹配的开始索引
public int start(int group):返回之前匹配操作中通过给定组所捕获序列的开始索引
public int end(): 返回最后匹配字符后的偏移量
public int end(int group):返回之前匹配操作中通过给定组所捕获序列的最后字符之后的偏移量
研究方法
研究方法(study methods)回顾输入的字符串,并且返回一个用于指示是否找到模式的布尔值
public boolean lookingAt(): 尝试从区域开头处开始,输入序列与该模式匹配
public boolean find(): 尝试地寻找输入序列中,匹配模式的下一个子序列
public boolean find(int start): 重置匹配器,然后从指定的索引处开始,尝试地寻找输入序列中,匹配模式的下一个子序列
public boolean matches(): 尝试将整个区域与模式进行匹配
替换方法
替换方法(replacement methods)用于在输入的字符串中替换文本有用处的方法
public Matcher appendReplacement(StringBuffer sb, String replacement):实现非结尾处的增加和替换操作
public StringBuffer appendTail(StringBuffer sb):实现结尾处的增加和替换操作
public String replaceAll(String replacement):使用给定的替换字符串来替换输入序列中匹配模式的每一个子序列
public String replaceFirst(String replacement):使用给定的替换字符串来替换输入序列中匹配模式的第一个子序列
public static String quoteReplacement(String s):返回指定字符串的字面值来替换字符串。这个方法会生成一个字符串,用作 Matcher 的 appendReplacement 方法中的字面值替换 s。所产生的字符串将与作为字面值序列的 s 中的字符序列匹配。斜线(\)和美元符号($)将不再有特殊意义了
使用start和end方法
示例程序用于计算输入序列中单词“dog”的出现次数
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MatcherDemo {
private static final String REGEX = "\\bdog\\b";
private static final String INPUT = "dog dog dog doggie dogg";
public static void main(String[] args) {
Pattern pattern = Pattern.compile(REGEX);
Matcher matcher = pattern.matcher(INPUT);
int count = 0;
while (matcher.find()) {
count++;
System.out.println("Match number" + count);
System.out.println("start():" + matcher.start());
System.out.println("end()" + matcher.end());
}
}
输出:
Match number1
start():0
end()3
Match number2
start():4
end()7
Match number3
start():8
end()11
可以看出,这个例子使用了单词边界,用于确保更长单词中的字母“dog“就不是子串了。它也输出一些有用的信息,在输入的字符串中什么地方有匹配。start方法返回在以前的匹配操作期间,由给定组所捕获子序列的开始处索引,end方法返回匹配到最后一个字符索引加1
使用matches和lookingAt方法
matches和lookingAt方法都是尝试该模式匹配输入序列。然而不同的是,matches要求匹配整个输入字符串,而lookingAt不是这样。这两个方法都是从输入字符串的开头开始。下面是示例代码:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MatchesLooking {
private static final String REGEX = "foo";
private static final String INPUT = "fooooooooooooooooo";
public static void main(String[] args) {
Pattern pattren = Pattern.compile(REGEX);
Matcher matcher = pattren.matcher(INPUT);
System.out.println("Current REGEX is: " + REGEX);
System.out.println("Current INPUT is: " + INPUT);
System.out.println("lookingAt():" + matcher.lookingAt());
System.out.println("matches():" + matcher.matches());
}
}
输出:
Current REGEX is: foo
Current INPUT is: fooooooooooooooooo
lookingAt():true
matches():false
使用replaceFirst(String)和replaceAll(String)方法
replaceFirst和replaceAll方法替换匹配给定正则表达式的文本。从它们的名字可以看出,replaceFirst替换第一个匹配到的,而replaceAll替换所有匹配的。下面是示例代码:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ReplaceDemo {
private static String REGEX = "dog";
private static String INPUT = "The dog says meow. All dogs say meow.";
private static String REPLACE = "cat";
public static void main(String[] args) {
Pattern p = Pattern.compile(REGEX);
Matcher m = p.matcher(INPUT); // 获得匹配器对象
INPUT = m.replaceAll(REPLACE);
System.out.println(INPUT);
}
}
输出:
The cat says meow. All cats say meow.
在上面的例子中,所有的dog都被替换成了cat。但是为什么在这里停下来了呢?你可以替换匹配任何正则表达式的文本,这样优于替换一个简单的像dog一样的文字。这个方法的API描述了给定正则表达式“a*b”,再输入‘aabfooaabfooabfoob’和替换的字符串是'-'情况下,表达式的匹配器调用方法后,会产生字符串‘-foo-foo-foo- ’
下面是示例代码:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ReplaceDemo2 {
private static String REGEX = "a*b";
private static String INPUT = "aabfooaabfooabfoob";
private static String REPLACE = "-";
public static void main(String[] args) {
Pattern p = Pattern.compile(REGEX);
Matcher m = p.matcher(INPUT); // 获得匹配器对象
INPUT = m.replaceAll(REPLACE);
System.out.println(INPUT);
}
}
输出:
-foo-foo-foo-
仅要替换模式一次时,可以简单地调用replaceFirst用于取代replaceAll,它接受同样的参数
在java.lang.String中等价的Matcher方法
为了使用方便,String 类看上去还不错地模仿了 Matcher 的两个方法:
public String replaceFirst(String regex, String replacement):使用给定的替换字符串替换该字符串中匹配了给定正则表达式的第一个子字符串。调用 str.replaceFirst(regex, repl)方法与使用Pattern.compile(regex).matcher(str).replaceFirst(repl)产生的结果是完全相同的
public String replaceAll(String regex, String replacement):使用给定的替换字符串替换该字符串中匹配了给定正则表达式的每一个子字符串。调用 str.replaceAll(regex, repl)方法与使用 Pattern.compile(regex).matcher(str).replaceAll(repl)产生的结果是完全相同的