正则表达式(Regular Expression,简称regex或regexp)是一种用于匹配字符串的强大工具。 它通过使用特定的语法规则来描述字符串的模式,从而可以在文本中进行搜索、替换和验证等操作。
正则表达式语法结构
字符 (Characters)
Construct | Matches |
---|---|
x | 字符 x |
\\ | 字符反斜杠 |
\0n | 八进制字符 \0n (0 ≤ n ≤ 7) |
\0nn | 八进制字符 \0nn (0 ≤ n ≤ 7) |
\0mnn | 八进制字符 \0mnn (0 ≤ m ≤ 3,0 ≤ n ≤ 7) |
\xhh | 十六进制字符 \0xhh |
\uhhhh | 十六进制字符 \0xhhhh |
\x{h…h} | 十六进制字符 \0xh…h (Character.MIN_CODE_POINT ≤ \0xh…h ≤ Character.MAX_CODE_POINT) |
\N{name} | Unicode 字符名为 ‘name` 的字符 |
\t | 制表符 tab(\u0009) |
\n | 换行符(\u000A) |
\r | 回车符(\u000D) |
\f | 换页符(\u000C) |
\a | 响铃字符(\u0007) |
\e | 转义字符(\u001B) |
\cx | x 对应的控制字符 |
字符集 (Character classes)
Construct | Matches |
---|---|
[abc] | a,b 或 c (简单字符集) |
[^abc] | 任意字符除了 a,b,c (否定字符集) |
[a-zA-Z] | 所有小写字母(a-z)或所有大写字母(A-Z)(字符范围) |
[a-d[m-p]] | 字母 a-d 或 m-p(并集) |
[a-z&&[def]] | d,e 或 f(交集) |
[a-z&&[^bc]] | 字母 a-z 除了 b,c。等价于 [ad-z] |
[a-z&&[^m-p]] | 字母 a-z 除了 m-p。等价于 [a-lq-z] |
预定义字符集
Construct | Matches |
---|---|
. | 一个任意字符,除了行终止符 |
\d | 一个数字。等价于 [0-9] |
\D | 一个非数字字符。等价于 [^0-9] 或 [^\d] |
\h | 一个水平空白符。等价于 [ \t\xA0\u1680\u180e\u2000-\u200a\u202f\u205f\u3000] |
\H | 一个非水平空白符字符。等价于 [^\h] |
\s | 一个空白字符。等价于:[ \t\n\x0B\f\r] |
\S | 一个非空白字符。等价于:[^\s] |
\v | 一个垂直空白字符。等价于:[\n\x0B\f\r\x85\u2028\u2029] |
\V | 一个非垂直空白字符字符。等价于:[^\v] |
\w | 一个单词字符(字母、数字、下划线)。等价于:[a-zA-Z_0-9] |
\W | 一个非单词字符。等价于:[^\w] |
POSIX 字符集 (仅限 US-ASCII)
Construct | Matches |
---|---|
\p{Lower} | 一个小写字母。等价于:[a-z] |
\p{Upper} | 一个大写字母。等价于:[A-Z] |
\p{ASCII} | 一个 ASCII 字符。等价于:[\x00-\x7F] |
\p{Alpha} | 一个字母字符。等价于:[\p{Lower}\p{Upper}] |
\p{Digit} | 一个数字。等价于:[0-9] |
\p{Alnum} | 一个字母或数字字符。等价于:[\p{Aplha}\p{Digit}] |
\p{Punct} | 一个标点符号。等价于:[!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~] |
\p{Graph} | 一个可见字符。等价于:[\p{Alnum}\p{Punct}] |
\p{Print} | 一个可打印字符。等价于:[\p{Graph}\x20] |
\p{Blank} | 一个空格或制表符(tab)。等价于:[ \t] |
\p{Cntrl} | 一个控制字符。等价于:[\x00-\x1F\x7F] |
\p{XDigit} | 一个十六进制数字。等价于:[0-9a-fA-F] |
\p{Space} | 一个空白字符。等价于:[ \t\n\x0B\f\r] |
java.lang.Character 字符集
简单 Java 字符类型
Construct | Matches |
---|---|
\p{javaLowerCase} | 相当于 java.lang.Character.isLowerCase() |
\p{javaUpperCase} | 相当于 java.lang.Character.isUpperCase() |
\p{javaWhitespace} | 相当于 java.lang.Character.isWhitespace() |
\p{javaMirrored} | 相当于 java.lang.Character.isMirrored() |
Unicode Scripts, blocks, categories, binary properties 字符集
Unicode 脚本、块、类别和二进制属性都是用 \p
和 \P
结构编写(和 Perl 中一样),可以在字符集内部和外部使用。
如果输入具有属性 prop,则 \p{prop}
匹配,\P{prop}
不匹配。
脚本(Scripts)
可以用前缀
Is
来指定,例如IsHiragana
,或者使用关键字script
(或其缩写形式sc
)。例如:script=Hiragana
或sc=Hiragana
。有效的 Script 命名参考 UnicodeScript.forName.
块(Blocks)
可以用前缀
In
来指定,例如InMongolian
,或者使用关键字block
(或其缩写形式blk
)。例如:block=Mongolian
或blk=Mongolian
。有效的 Block 命名参考 UnicodeBlock.forName.
类别(Categories)
可以用前缀
Is
来指定。\p{L}
和\p{IsL}
都表示 Unicode 字母。或者使用关键字general_category
(或其缩写形式gc
)。例如:general_category=Lu
或gc=Lu
。二进制属性(Binary Properties)
以
Is
为前缀指定,例如:IsAlphabetic
。java.util.regex.Pattern 支持的二进制属性有:- Alphabetic
- Ideographic
- Letter
- Lowercase
- Uppercase
- Titlecase
- Punctuation
- White_Space
- Digit
- Hex_Digit
- Join_Control
- Noncharacter_Code_Point
- Assigned
Construct | Matches |
---|---|
\p{IsLatin} | 一个拉丁字母 (script) |
\p{InGreek} | 一个希腊字母块中的字符 (block) |
\p{Lu} | 一个大写字母 (category) |
\p{IsAlphabetic} | 一个字母字符 (binary property) |
\p{Sc} | 一个货币符号 |
\P{InGreek} | 除希腊字母块中的字符之外的任意一个字符 |
[\p{L}&&^\p{Lu} | 除了大写字母外的任意一个字符 |
匹配器
边界匹配器
Construct | Matches |
---|---|
^ | 输入的开头 |
$ | 输入的结尾 |
\b | 单词的边界 |
\b{g} | Unicode 扩展字形边界 |
\B | 非单词边界 |
\A | 输入的开始 |
\G | 上一次匹配的结尾 |
\Z | 输入的结束除最后的行终止符 |
\z | 输入的结尾 |
^
和 $
会忽略行终止符,并且仅匹配整个输入序列的开头和结尾。
如果使用 MULTLINE
模式,^
匹配输入的开头和除输入结尾之外的任何行终止符之后,$
匹配行终止符之前和输入序列结尾换行匹配器
Construct | Matches |
---|---|
\R | 任意的 Unicode 换行序列。 等价于: \u000D\u000A|[\u000A\u000B\u000C\u000D\u0085\u2028\u2029] |
Unicode 扩展字形匹配器
字形是构成文字的最小单元,通常对应于一个可视字符,但它可能由多个 Unicode 字符组合而成(例如,表情符号、附加符号、复合字符等)。 Unicode 扩展字形匹配器的作用是识别并处理这些复杂的字符组合。
Construct | Matches |
---|---|
\X | 任意的 Unicode 扩展字形 |
逻辑运算符
Construct | Matches |
---|---|
XY | X 后跟着 Y |
X|Y | X 或 Y |
(X) | X 作为捕获组 |
量词
贪婪量词
贪婪量词(Greedy Quantifiers)尽可能多地匹配字符,直到整个模式匹配成功。如果后面的模式不能匹配,它会回溯并增加匹配的字符数。
Construct | Matches |
---|---|
X? | 匹配前面的元素 X,0 次或 1 次 |
X* | 匹配前面的元素 X,0 次或多次 |
X+ | 匹配前面的元素 X,1 次或多次 |
X{n} | 匹配前面的元素 X,n 次 |
X{n,m} | 匹配前面的元素 X,至少 n 次但不超过 m 次 |
懒惰量词
懒惰量词(也称不情愿量词,Reluctant Quantifiers)尽量少地匹配字符,尽可能减少匹配的字符数,直到整个模式匹配成功。
语法:在贪婪量词后面接 ?
。
Construct | Matches |
---|---|
X?? | 匹配前面的元素 X, 0 次或 1 次 |
X*? | 匹配前面的元素 X,0 次或多次 |
X+? | 匹配前面的元素 X,1 次或多次 |
X{n}? | 匹配前面的元素 X,n 次 |
X{n,m}? | 匹配前面的元素 X,至少 n 次但不超过 m 次 |
占有量词
占有量词(Possessive Quantifiers)与贪婪量词类似,但不会回溯。匹配后无法撤销,如果无法匹配后续内容,则匹配失败。
语法:在贪婪量词后面接 +
。
Construct | Matches |
---|---|
X?+ | 匹配前面的元素 X, 0 次或 1 次 |
X*+ | 匹配前面的元素 X,0 次或多次 |
X++ | 匹配前面的元素 X,1 次或多次 |
X{n}+ | 匹配前面的元素 X,n 次 |
X{n,m}+ | 匹配前面的元素 X,至少 n 次但不超过 m 次 |
为了区分三种量词,我们可以通过正则表达式匹配字符串 aabb
:
- 贪婪量词:
(.*)(b+)
。匹配结果:group 1:aab
,group 2:b
- 懒惰量词:
(.*?)(b+)
。匹配结果:group 1:aa
,group 2:bb
- 占有量词:
(.*+)(b+)
。匹配结果:匹配失败
修饰符
Construct | Matches |
---|---|
(?idmsuxU-idmsuxU) | 设置修饰符开关(启用 / 禁用)(修饰符: i d m s u x U) |
各个修饰符简要说明:
修饰符 | Java 定义 说明 | |
---|---|---|
i | CASE_INSENSITIVE | 默认忽略 US-ASCII 字符大小写。如需忽略 Unicode 字符大小写,需要搭配 UNICODE_CASE 使用 启用此修饰符可能会造成轻微的性能损失 |
d | UNIX_LINES | 启用 Unix 行模式。^ 和 $ 仅识别 \n 行终止符 |
m | MULTILINE | 启用多行模式。^ 和 $ 分别匹配行终止符或输入序列结尾之后或之前的位置。默认情况下,^ 和 $ 仅匹配整个输入序列的开头和结尾。 |
s | DOTALL | 在 dotall 模式下,. 匹配任何字符,包括行终止符。默认情况下,. 不匹配行终止符。 |
u | UNICODE_CASE | 使用此标识,确保在使用 CASE_INSENSITIVE 时可以正确处理 Unicode 字符的大小转换 启用该修饰符可能会造成性能损失 |
x | COMMENTS | 允许模式中存在空格和注释。 在这种模式下,空格会被忽略,并且以 # 开头的嵌入注释也会被忽略,直到行尾为止。 |
U | UNICODE_CHARACTER_CLASS | 启用预定义字符类和 POSIX 字符类的 Unicode 版本。 启用该修饰符可能会造成性能损失 |
示例,配置 Case insensitive 修饰符正则表达式写法:
- 启用修饰符
(?i)
- 禁用修饰符
(?-i)
修饰符只对修饰符之后的内容有效。
例如,要全局忽略大小写匹配 “abc”,则应该这样写 (?i)abc
,而不能 a(?i)bc
。a(?i)bc
仅代表 “bc” 忽略大小写。
分组与捕获
Construct | Matches |
---|---|
(?<name>X) | $X$,作为一个命名捕获组(named-capturing group),命名为 “name” |
(?:X) | $X$,作为一个非捕获组(non-capturing group) |
(?idmsuxU-idmsuxU:X) | $X$,具有特定修饰符的捕获组(修饰符: i d m s u x U) |
以
(?
开头的组要么是纯粹的非捕获组,不会捕获文本并且不计入组总数,要么是命名捕获组
分组组号
分组组号是通过左括号从左到右来编号的。例如,正则表达式 ((A)(B(C)))
,有 4 个这样的组:
- ((A)(B(C)))
- (A)
- (B(C))
- (C)
0 组始终代表表达式捕获的整个字符串。
在匹配过程中,与该组匹配的输入序列的每个子序列都会被保存。捕获的子序列可以通过反向引用在表达式中使用,也可以在匹配操作完成后从匹配器中检索。
分组名
也可以为分组命名,即命名捕获组。后续也可以通过分组名进行反向引用,在匹配操作完成后也可以通过分组名从匹配器中获取。
使用命名捕获组后仍会为组进行编号。
组名由以下字符组成:(第一个字符必须是字母)
- 数字
0-9
(\u0030
-\u0039
) - 大写字母
A-Z
(\u0041
-\u005a
) - 小写字母
a-z
(\u0061
-\u007a
)
反向引用
Construct | Matches |
---|---|
\n | 第 $n$ 个捕获组匹配的内容 |
\k<name> | 命名捕获组 “name” 匹配的内容 |
捕获组与量词
当对捕获组使用量词时,捕获组会覆盖之前的捕获值,只保留最后一次迭代的捕获。如果二次捕获时失败则捕获组内是上一次捕获的结果(如果有)。
示例:
使用正则表达式 (a(b)?)+
匹配字符串 "aba"
。最终得到的捕获组为:
- 捕获组 1
"ab"
- 捕获组 2
"b"
TIP: 可以在重复量词外部使用捕获组来捕获所有的匹配。
非捕获组与独立非捕获组对比
非捕获组 (?:X)
与 独立非捕获组(?>X)
的区别:
特性 | 非捕获组((?:X) ) | 独立非捕获组((?>X) ) |
---|---|---|
捕获分组 | 否 | 否 |
回溯行为 | 允许回溯,正则引擎会尝试不同的匹配选项 | 不允许回溯,分组内的匹配一旦成功就不会尝试其他匹配选项 |
用途 | 用于分组,但不捕获匹配结果 | 用于优化匹配过程,避免回溯,提高效率 |
性能 | 性能较为普通,回溯可能会发生 | 性能较高,适用于优化匹配过程中的回溯 |
匹配失败时的行为 | 如果匹配失败,可以回溯尝试 | 如果匹配失败,不会回溯,导致匹配失败 |
零宽断言
Construct | Matches |
---|---|
(?=X) | 零宽正向先行断言(Zero-width Positive Lookahead) |
(?!X) | 零宽负向先行断言(Zero-width Negative Lookahead) |
(?<=X) | 零宽正向回顾断言(Zero-width Positive Lookbehind) |
(?<!X) | 零宽负向回顾断言(Zero-width Negative Lookbehind) |
(?>X) | 独立非捕获组(Independent Non-capturing Group) |
零宽断言是一种特殊的匹配机制,它们允许根据周围的文本条件来控制匹配,但本身不匹配任何字符。
- 正向先行断言
(?=X)
:匹配当前位置后面跟着X
的文本 - 负向先行断言
(?!X)
:匹配当前位置后面没有跟着X
的文本 - 正向回顾断言
(?<=X)
:匹配当前位置前面有X
的文本 - 负向回顾断言
(?<!X)
:匹配当前位置前面没有X
的文本
转义
Construct | Matches |
---|---|
\ | 转义字符,用于将紧随其后的字符从特殊意义转换为普通字符 |
\Q | 开始引用,后面的所有字符都作为字面量处理,直到遇到 \E 。 |
\E | 结束引用,标志着一个引用区域的结束 |
示例说明:
当需要匹配一个正则表达式元字符的字符串,如 a.b*c
,如果不转义,就会遇到问题,因为正则表达式会试图将 .
和 *
解释为元字符。
这时可以通过如下方式进行匹配:
使用转义字符
\
regex1
a\.b\*c
使用
\Q
和\E
regex1
\Qa.b*c\E
附录: 行终止符
原文参考:Line terminators
.
默认不能匹配的行终止符。行终止符是一或两个字符序列,用于标记输入字符序列的行尾。以下字符可识别为行终止符:
- 换行符:
\n
- 回车符后接换行符:
\r\n
- 独立的回车符:
\r
- 下一行字符:
\u0085
- 行分隔符:
\u2028
- 段落分隔符:
\u2029
当使用 UNIX_LINES
模式(flag: (?d)
)时,行终止符仅代表换行符 \n
。
当使用 DOTALL
模式(flag:(?s)
)时,.
可以匹配行终止符。
常用正则表达式
注意:正则表达式并未转义。比如
\d
在 Java 中应使用\\d
。
IPv4 地址
|
|
中文
|
|
|
|
附录: Java API
A compiled representation of a regular expression.
A regular expression, specified as a string, must first be compiled into an instance of this class. The resulting pattern can then be used to create a Matcher
object that can match arbitrary character sequences against the regular expression. All of the state involved in performing a match resides in the matcher, so many matchers can share the same pattern.
A typical invocation sequence is thus
|
|
A matches
method is defined by this class as a convenience for when a regular expression is used just once. This method compiles an expression and matches an input sequence against it in a single invocation. The statement
|
|
is equivalent to the three statements above, though for repeated matches it is less efficient since it does not allow the compiled pattern to be reused.
Instances of this class are immutable and are safe for use by multiple concurrent threads. Instances of the Matcher
class are not safe for such use.
Summary of regular-expression constructs
Characters
Construct | Matches |
---|---|
x | The character x |
\\ | The backslash character |
\0 n | The character with octal value 0 n (0 <= n <= 7) |
\0 nn | The character with octal value 0 nn (0 <= n <= 7) |
\0 mnn | The character with octal value 0 mnn (0 <= m <= 3, 0 <= n <= 7) |
\x hh | The character with hexadecimal value 0x hh |
\u hhhh | The character with hexadecimal value 0x hhhh |
\x {h…h} | The character with hexadecimal value 0x h…h (Character.MIN_CODE_POINT <= 0x h…h <= Character.MAX_CODE_POINT ) |
\N{ name} | The character with Unicode character name ’name’ |
\t | The tab character ('\u0009' ) |
\n | The newline (line feed) character ('\u000A' ) |
\r | The carriage-return character ('\u000D' ) |
\f | The form-feed character ('\u000C' ) |
\a | The alert (bell) character ('\u0007' ) |
\e | The escape character ('\u001B' ) |
\c x | The control character corresponding to x |
Character classes
Construct | Matches |
---|---|
[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] (subtraction) |
Predefined character classes
Construct | Matches |
---|---|
. | Any character (may or may not match line terminators) |
\d | A digit: [0-9] |
\D | A non-digit: [^0-9] |
\h | A horizontal whitespace character: [ \t\xA0\u1680\u180e\u2000-\u200a\u202f\u205f\u3000] |
\H | A non-horizontal whitespace character: [^\h] |
\s | A whitespace character: [ \t\n\x0B\f\r] |
\S | A non-whitespace character: [^\s] |
\v | A vertical whitespace character: [\n\x0B\f\r\x85\u2028\u2029] |
\V | A non-vertical whitespace character: [^\v] |
\w | A word character: [a-zA-Z_0-9] |
\W | A non-word character: [^\w] |
POSIX character classes (US-ASCII only)
Construct | Matches |
---|---|
\p{Lower} | A lower-case alphabetic character: [a-z] |
\p{Upper} | An upper-case alphabetic character:[A-Z] |
\p{ASCII} | All ASCII:[\x00-\x7F] |
\p{Alpha} | An alphabetic character:[\p{Lower}\p{Upper}] |
\p{Digit} | A decimal digit: [0-9] |
\p{Alnum} | An alphanumeric character:[\p{Alpha}\p{Digit}] |
\p{Punct} | Punctuation: One of !"#$%&'()*+,-./:;<=>?@[\]^_ { |
\p{Graph} | A visible character: [\p{Alnum}\p{Punct}] |
\p{Print} | A printable character: [\p{Graph}\x20] |
\p{Blank} | A space or a tab: [ \t] |
\p{Cntrl} | A control character: [\x00-\x1F\x7F] |
\p{XDigit} | A hexadecimal digit: [0-9a-fA-F] |
\p{Space} | A whitespace character: [ \t\n\x0B\f\r] |
java.lang.Character classes
(simple java character type)
Construct | Matches |
---|---|
\p{javaLowerCase} | Equivalent to java.lang.Character.isLowerCase() |
\p{javaUpperCase} | Equivalent to java.lang.Character.isUpperCase() |
\p{javaWhitespace} | Equivalent to java.lang.Character.isWhitespace() |
\p{javaMirrored} | Equivalent to java.lang.Character.isMirrored() |
Classes for Unicode scripts, blocks, categories and binary properties
Construct | Matches |
---|---|
\p{IsLatin} | A Latin script character (script) |
\p{InGreek} | A character in the Greek block (block) |
\p{Lu} | An uppercase letter (category) |
\p{IsAlphabetic} | An alphabetic character (binary property) |
\p{Sc} | A currency symbol |
\P{InGreek} | Any character except one in the Greek block (negation) |
[\p{L}&&[^\p{Lu}]] | Any letter except an uppercase letter (subtraction) |
Boundary matchers
Construct | Matches |
---|---|
^ | The beginning of a line |
$ | The end of a line |
\b | A word boundary |
\b{g} | A Unicode extended grapheme cluster 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 |
Linebreak matcher
Construct | Matches |
---|---|
\R | Any Unicode linebreak sequence, is equivalent to `\u000D\u000A |
Unicode Extended Grapheme matcher
Construct | Matches |
---|---|
\X | Any Unicode extended grapheme cluster |
Greedy quantifiers
Construct | Matches |
---|---|
X? | X, once or not at all |
X* | X, zero or more times |
X+ | X, one or more times |
X{ n} | X, exactly n times |
X{ n, } | X, at least n times |
X{ n, m} | X, at least n but not more than m times |
Reluctant quantifiers
Construct | Matches |
---|---|
X?? | X, once or not at all |
X*? | X, zero or more times |
X+? | X, one or more times |
X{ n}? | X, exactly n times |
X{ n,}? | X, at least n times |
X{ n, m}? | X, at least n but not more than m times |
Possessive quantifiers
Construct | Matches |
---|---|
X?+ | X, once or not at all |
X*+ | X, zero or more times |
X++ | X, one or more times |
X{ n}+ | X, exactly n times |
X{ n,}+ | X, at least n times |
X{ n, m}+ | X, at least n but not more than m times |
Logical operators
Construct | Matches |
---|---|
XY | X followed by Y |
X| Y | Either X or Y |
( X) | X, as a capturing group |
Back references
Construct | Matches |
---|---|
\ n | Whatever the nth capturing group matched |
\ k<name> | Whatever the named-capturing group “name” matched |
Quotation
Construct | Matches |
---|---|
\ | Nothing, but quotes the following character |
\Q | Nothing, but quotes all characters until \E |
\E | Nothing, but ends quoting started by \Q |
Special constructs (named-capturing and non-capturing)
Construct | Matches |
---|---|
(?<name> X) | X, as a named-capturing group |
(?: X) | X, as a non-capturing group |
(?idmsuxU-idmsuxU) | Nothing, but turns match flags i d m s u x U on - off |
(?idmsuxU-idmsuxU: X) | X, as a non-capturing group with the given flags i d m s u x U on - off |
(?= X) | X, via zero-width positive lookahead |
(?! X) | X, via zero-width negative lookahead |
(?<= X) | X, via zero-width positive lookbehind |
(?<! X) | X, via zero-width negative lookbehind |
(?> X) | X, as an independent, non-capturing group |
Backslashes, escapes, and quoting
The backslash character ('\'
) serves to introduce escaped constructs, as defined in the table above, as well as to quote characters that otherwise would be interpreted as unescaped constructs. Thus the expression \\
matches a single backslash and \{
matches a left brace.
It is an error to use a backslash prior to any alphabetic character that does not denote an escaped construct; these are reserved for future extensions to the regular-expression language. A backslash may be used prior to a non-alphabetic character regardless of whether that character is part of an unescaped construct.
Backslashes within string literals in Java source code are interpreted as required by The Java Language Specification as either Unicode escapes (section 3.3) or other character escapes (section 3.10.6) It is therefore necessary to double backslashes in string literals that represent regular expressions to protect them from interpretation by the Java bytecode compiler. The string literal "\b"
, for example, matches a single backspace character when interpreted as a regular expression, while "\\b"
matches a word boundary. The string literal "\(hello\)"
is illegal and leads to a compile-time error; in order to match the string (hello)
the string literal "\\(hello\\)"
must be used.
Character Classes
Character classes may appear within other character classes, and may be composed by the union operator (implicit) and the intersection operator (&&
). The union operator denotes a class that contains every character that is in at least one of its operand classes. The intersection operator denotes a class that contains every character that is in both of its operand classes.
The precedence of character-class operators is as follows, from highest to lowest:
Precedence | Name | Example |
---|---|---|
1 | Literal escape | \x |
2 | Grouping | [...] |
3 | Range | a-z |
4 | Union | [a-e][i-u] |
5 | Intersection | [a-z&&[aeiou]] |
Note that a different set of metacharacters are in effect inside a character class than outside a character class. For instance, the regular expression .
loses its special meaning inside a character class, while the expression -
becomes a range forming metacharacter.
Line terminators
A line terminator is a one- or two-character sequence that marks the end of a line of the input character sequence. The following are recognized as line terminators:
- A newline (line feed) character (
'\n'
), - A carriage-return character followed immediately by a newline character (
"\r\n"
), - A standalone carriage-return character (
'\r'
), - A next-line character (
'\u0085'
), - A line-separator character (
'\u2028'
), or - A paragraph-separator character (
'\u2029'
).
If UNIX_LINES
mode is activated, then the only line terminators recognized are newline characters.
The regular expression .
matches any character except a line terminator unless the DOTALL
flag is specified.
By default, the regular expressions ^
and $
ignore line terminators and only match at the beginning and the end, respectively, of the entire input sequence. If MULTILINE
mode is activated then ^
matches at the beginning of input and after any line terminator except at the end of input. When in MULTILINE
mode $
matches just before a line terminator or the end of the input sequence.
Groups and capturing
Group number
Capturing groups are numbered by counting their opening parentheses from left to right. In the expression ((A)(B(C)))
, for example, there are four such groups:
((A)(B(C)))
(A)
(B(C))
(C)
Group zero always stands for the entire expression.
Capturing groups are so named because, during a match, each subsequence of the input sequence that matches such a group is saved. The captured subsequence may be used later in the expression, via a back reference, and may also be retrieved from the matcher once the match operation is complete.
Group name
A capturing group can also be assigned a “name”, a named-capturing group
, and then be back-referenced later by the “name”. Group names are composed of the following characters. The first character must be a letter
.
- The uppercase letters
'A'
through'Z'
('\u0041'
through'\u005a'
), - The lowercase letters
'a'
through'z'
('\u0061'
through'\u007a'
), - The digits
'0'
through'9'
('\u0030'
through'\u0039'
),
A named-capturing group
is still numbered as described in Group number.
The captured input associated with a group is always the subsequence that the group most recently matched. If a group is evaluated a second time because of quantification then its previously-captured value, if any, will be retained if the second evaluation fails. Matching the string "aba"
against the expression (a(b)?)+
, for example, leaves group two set to "b"
. All captured input is discarded at the beginning of each match.
Groups beginning with (?
are either pure, non-capturing groups that do not capture text and do not count towards the group total, or named-capturing group.
Unicode support
This class is in conformance with Level 1 of Unicode Technical Standard #18: Unicode Regular Expressions, plus RL2.1 Canonical Equivalents and RL2.2 Extended Grapheme Clusters.
Unicode escape sequences such as \u2014
in Java source code are processed as described in section 3.3 of The Java Language Specification. Such escape sequences are also implemented directly by the regular-expression parser so that Unicode escapes can be used in expressions that are read from files or from the keyboard. Thus the strings "\u2014"
and "\\u2014"
, while not equal, compile into the same pattern, which matches the character with hexadecimal value 0x2014
.
A Unicode character can also be represented by using its Hex notation (hexadecimal code point value) directly as described in construct \x{...}
, for example a supplementary character U+2011F can be specified as \x{2011F}
, instead of two consecutive Unicode escape sequences of the surrogate pair \uD840``\uDD1F
.
Unicode character names are supported by the named character construct \N{
…}
, for example, \N{WHITE SMILING FACE}
specifies character \u263A
. The character names supported by this class are the valid Unicode character names matched by Character.codePointOf(name)
.
Unicode extended grapheme clusters are supported by the grapheme cluster matcher \X
and the corresponding boundary matcher \b{g}
.
Unicode scripts, blocks, categories and binary properties are written with the \p
and \P
constructs as in Perl. \p{
prop}
matches if the input has the property prop, while \P{
prop}
does not match if the input has that property.
Scripts, blocks, categories and binary properties can be used both inside and outside of a character class.
Scripts are specified either with the prefix Is
, as in IsHiragana
, or by using the script
keyword (or its short form sc
) as in script=Hiragana
or sc=Hiragana
.
The script names supported by Pattern
are the valid script names accepted and defined by UnicodeScript.forName
.
Blocks are specified with the prefix In
, as in InMongolian
, or by using the keyword block
(or its short form blk
) as in block=Mongolian
or blk=Mongolian
.
The block names supported by Pattern
are the valid block names accepted and defined by UnicodeBlock.forName
.
Categories may be specified with the optional prefix Is
: Both \p{L}
and \p{IsL}
denote the category of Unicode letters. Same as scripts and blocks, categories can also be specified by using the keyword general_category
(or its short form gc
) as in general_category=Lu
or gc=Lu
.
The supported categories are those of The Unicode Standard in the version specified by the Character
class. The category names are those defined in the Standard, both normative and informative.
Binary properties are specified with the prefix Is
, as in IsAlphabetic
. The supported binary properties by Pattern
are
- Alphabetic
- Ideographic
- Letter
- Lowercase
- Uppercase
- Titlecase
- Punctuation
- Control
- White_Space
- Digit
- Hex_Digit
- Join_Control
- Noncharacter_Code_Point
- Assigned
The following Predefined Character classes and POSIX character classes are in conformance with the recommendation of Annex C: Compatibility Properties of Unicode Technical Standard #18: Unicode Regular Expressions, when UNICODE_CHARACTER_CLASS
flag is specified.
Classes | Matches |
---|---|
\p{Lower} | A lowercase character:\p{IsLowercase} |
\p{Upper} | An uppercase character:\p{IsUppercase} |
\p{ASCII} | All ASCII:[\x00-\x7F] |
\p{Alpha} | An alphabetic character:\p{IsAlphabetic} |
\p{Digit} | A decimal digit character:\p{IsDigit} |
\p{Alnum} | An alphanumeric character:[\p{IsAlphabetic}\p{IsDigit}] |
\p{Punct} | A punctuation character:\p{IsPunctuation} |
\p{Graph} | A visible character: [^\p{IsWhite_Space}\p{gc=Cc}\p{gc=Cs}\p{gc=Cn}] |
\p{Print} | A printable character: [\p{Graph}\p{Blank}&&[^\p{Cntrl}]] |
\p{Blank} | A space or a tab: [\p{IsWhite_Space}&&[^\p{gc=Zl}\p{gc=Zp}\x0a\x0b\x0c\x0d\x85]] |
\p{Cntrl} | A control character: \p{gc=Cc} |
\p{XDigit} | A hexadecimal digit: [\p{gc=Nd}\p{IsHex_Digit}] |
\p{Space} | A whitespace character:\p{IsWhite_Space} |
\d | A digit: \p{IsDigit} |
\D | A non-digit: [^\d] |
\s | A whitespace character: \p{IsWhite_Space} |
\S | A non-whitespace character: [^\s] |
\w | A word character: [\p{Alpha}\p{gc=Mn}\p{gc=Me}\p{gc=Mc}\p{Digit}\p{gc=Pc}\p{IsJoin_Control}] |
\W | A non-word character: [^\w] |
Categories that behave like the java.lang.Character boolean ismethodname methods (except for the deprecated ones) are available through the same \p{
prop}
syntax where the specified property has the name java*methodname*
.
Comparison to Perl 5
The Pattern
engine performs traditional NFA-based matching with ordered alternation as occurs in Perl 5.
Perl constructs not supported by this class:
- The backreference constructs,
\g{
n}
for the nthcapturing group and\g{
name}
for named-capturing group. - The conditional constructs
(?(
condition)
X)
and(?(
condition)
X|
Y)
, - The embedded code constructs
(?{
code})
and(??{
code})
, - The embedded comment syntax
(?#comment)
, and - The preprocessing operations
\l
\u
,\L
, and\U
.
Constructs supported by this class but not by Perl:
- Character-class union and intersection as described above.
Notable differences from Perl:
- In Perl,
\1
through\9
are always interpreted as back references; a backslash-escaped number greater than9
is treated as a back reference if at least that many subexpressions exist, otherwise it is interpreted, if possible, as an octal escape. In this class octal escapes must always begin with a zero. In this class,\1
through\9
are always interpreted as back references, and a larger number is accepted as a back reference if at least that many subexpressions exist at that point in the regular expression, otherwise the parser will drop digits until the number is smaller or equal to the existing number of groups or it is one digit. - Perl uses the
g
flag to request a match that resumes where the last match left off. This functionality is provided implicitly by theMatcher
class: Repeated invocations of thefind
method will resume where the last match left off, unless the matcher is reset. - In Perl, embedded flags at the top level of an expression affect the whole expression. In this class, embedded flags always take effect at the point at which they appear, whether they are at the top level or within a group; in the latter case, flags are restored at the end of the group just as in Perl.
For a more precise description of the behavior of regular expression constructs, please see Mastering Regular Expressions, 3rd Edition, Jeffrey E. F. Friedl, O’Reilly and Associates, 2006.
感谢您的耐心阅读!来选个表情,或者留个评论吧!