Java正则表达式再学习

为什么叫Java正则表达式再学习,在很久之前写过一篇《Java正则表达式》的博客,但好久没有用过了,所以再拿出来梳理一下。

Java的正则表达式的工具在java.util.regex包下,有一个接口MatchResult,两个类Matcher,Pattern,还有一个Exceptions:PatternSyntaxException。

首先来看Pattern类

API地址:https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html#cg

签名:

public final class Pattern extends Object implements Serializable

是一个正则表达式的编译的版本。一个string类型的正则表达式,如果想要使用的话,必须首先要编译成Pattern的实例。编译后的pattern可以用来匹配任意的字符串序列并得到结果Matcher。匹配过程中所有的结果都会保存在Matcher当中,所以很多的matchers都会共享同一个pattern。

一个典型的使用样例如下:

Pattern p = Pattern.compile("a*b");
Matcher m = p.matcher("aaaaab");
boolean b = m.matches();

同时在Pattern中有一个便于使用的方法matches(),当我们仅仅需要匹配一次的时候,这个就很好用。如下:

boolean b = Pattern.matches("a*b", "aaaaab");

其实实际上是和上面的3行代码一样的。

还有一点就是Pattern类是线程安全的,Matcher在这种使用情况下,不是线程安全的。

Summary of regular-expression constructs

Construct Matches
Characters
x The character x
\\ The backslash character
\0n The character with octal value 0n (0 <= n <= 7)
\0nn The character with octal value 0nn (0 <= n <= 7)
\0mnn The character with octal value 0mnn (0 <= m <= 3, 0 <= n <= 7)
\xhh The character with hexadecimal value 0xhh
\uhhhh The character with hexadecimal value 0xhhhh
\x{h…h} The character with hexadecimal value 0xh…h (Character.MIN_CODE_POINT  <= 0xh…h <=  Character.MAX_CODE_POINT)
\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')
\cx The control character corresponding to x
Character classes
[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
. 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]
POSIX character classes (US-ASCII only)
\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)
\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
\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
^ 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
Greedy quantifiers(贪婪模式)
X? X, once or not at all        0,1
X* X, zero or more times     0,1…n
X+ X, one or more times      1,2…n
X{n} X, exactly n times           n
X{n,} X, at least n times          >=n
X{n,m} X, at least n but not more than m times     n->m
Reluctant quantifiers(勉强模式)
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(侵占模式)
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
XY X followed by Y
X|Y Either X or Y
(X) X, as a capturing group
Back references
\n Whatever the nth capturing group matched
\k<name> Whatever the named-capturing group “name” matched
Quotation
\ 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)
(?<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
(?idmsux-idmsux:X) X, as a non-capturing group with the given flags i d m s u x 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

反斜杠(‘\’)充当的角色是引入注释。上面表格中所示,\为注释后面的部分,\Q…\E则是注释从\Q到\E的部分(quote)。

不要在任何字母之前使用反斜杠,因为这些字符是以后可能用来扩展正则表达式语言所需要的,而且不管后面的字符是不是正则表达式的一部分,转义的处理要优先字母的匹配。

在Java中,根据Java的规范,反斜扛要两个才行,比如\b匹配的是空格,在Java中,要使用\\b才可以。比如”\(hello\)”匹配的是字符串(hello),但实际上要使”\\(hello\\)”才能实现。
Character Classes

一些字符串会匹配在另外一些字符中间,也可能这些字符是由连接符或者交集符(&&)组合在一起。其运算顺序从高往低依次是:

1 Literal escape \x
2 Grouping [...]
3 Range a-z
4 Union [a-e][i-u]
5 Intersection [a-z&&[aeiou]]

 

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

groups是从左到有根据左括号来判断。比如在表达式((A)(B(C)))中,有以下的分组

1 ((A)(B(C)))
2 (A)
3 (B(C))
4 (C)

其中group(0)=整个表达式。groups的分组这样来分,是因为输入序列的每一个字片段的匹配都会被保存下来。这些片段可能在以后的表达式中会被用到。具体的分就是根据括号从左到右依次括号括起来的范围,比如上面的((A)(B(C))),第0个括号,就是整个的分组,即全部的表达式;而第1个括号,此处其实也是全部内容都包括起来了;第2个括号则是仅仅包括了(A);第3个括号则是包括了(B(C));第4个括号则是(C)。有以下代码可以参考:

    String patternString = "((A)(B(C)))";
    Pattern pattern = Pattern.compile(patternString);
    Matcher matcher = pattern.matcher("DABCDEF");
    if(matcher.find()) {
      System.out.println("Found:" + matcher.pattern().pattern());
    }else {
      System.out.println("Not Found:" + matcher.pattern().pattern());
    }

    //Group 0 = ABC
    //Group 1 = ABC
    //Group 2 = A
    //Group 3 = BC
    //Group 4 = C
    System.out.println("Group 0 :" + matcher.group(0));
    System.out.println("Group 1 :" + matcher.group(1));
    System.out.println("Group 2 :" + matcher.group(2));
    System.out.println("Group 3 :" + matcher.group(3));
    System.out.println("Group 4 :" + matcher.group(4));

输出结果为:

Found:((A)(B(C)))
Group 0 :ABC
Group 1 :ABC
Group 2 :A
Group 3 :BC
Group 4 :C

 

Group name

一个片段可以起一个名字“name”,称作named-capturing group。名字可以有大小写字母和数字构成A-Za-z0-9,注意,第一个字符必须为字母。

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.

起名字的方式是在相应的group当中添加?<name>来完成,比如(pattern)为(?<name>pattern)

String patternString = "((A)(B(?<nameC>C)))";

这里面的名字就是nameC

Unicode support

This class is in conformance with Level 1 of Unicode Technical Standard #18: Unicode Regular Expression, plus RL2.1 Canonical Equivalents.

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 in a regular-expression 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 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
  • Noncharacter_Code_Point
  • Assigned

 

Predefined Character classes and POSIX character classes are in conformance with the recommendation of Annex C: Compatibility Properties of Unicode Regular Expression , 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}]
\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 javamethodname.

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:

  • Predefined character classes (Unicode character)\h    A horizontal whitespace\H    A non horizontal whitespace\v    A vertical whitespace

    \V    A non vertical whitespace

    \R    Any Unicode linebreak sequence \u000D\u000A|[\u000A\u000B\u000C\u000D\u0085\u2028\u2029]

    \X    Match Unicode extended grapheme cluster

  • The backreference constructs, \g{n} for the nthcapturing group and \g{name} for named-capturing group.
  • The named character construct, \N{name} for a Unicode character by its name.
  • 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 than 9 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 the Matcher class: Repeated invocations of the find 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, 3nd Edition, Jeffrey E. F. Friedl, O’Reilly and Associates, 2006.

 

Java 6、PCRE、Perl支持使用正则记号<\Q>和<\E>。<\Q>会抑制所有元字符的含义,直到出现<\E>为止。如果漏掉了<\E>,那么在<\Q>之后直到正则表达式结束之前的所有字符都会被当作字符文本来对待。所以下面的的两个正则表达式为一个意思:

Pattern p = Pattern.compile("\\$\\(\\)\\*\\+\\.\\?\\[\\\\\\^\\{\\|");
Matcher m = p.matcher("$()*+.?[\\^{|");
boolean b = m.matches();

Pattern p = Pattern.compile("\\Q$()*+.?[\\^{|\\E");
Matcher m = p.matcher("$()*+.?[\\^{|");

 

Pattern的方法比较简单,主要如下:

Modifier and Type Method and Description
static Pattern compile(String regex)

Compiles the given regular expression into a pattern.
static Pattern compile(String regex, int flags)

Compiles the given regular expression into a pattern with the given flags.
int flags()

Returns this pattern’s match flags.
Matcher matcher(CharSequence input)

Creates a matcher that will match the given input against this pattern.
static boolean matches(String regex, CharSequence input)

Compiles the given regular expression and attempts to match the given input against it.
String pattern()

Returns the regular expression from which this pattern was compiled. 返回所编译的正则表达式
static String quote(String s)

Returns a literal pattern String for the specified String. 将s使用\Q…\E包围起来,使得其中的元字符不需转义
String[] split(CharSequence input)

Splits the given input sequence around matches of this pattern.
String[] split(CharSequence input, int limit)

Splits the given input sequence around matches of this pattern.
String toString()

Returns the string representation of this pattern.

其中要注意的是,Pattern有几个flags,可以设置匹配的原则:

 

public String[] split(CharSequence input,
                      int limit)
围绕此模式的匹配拆分给定输入序列。此方法返回的数组包含输入序列的子字符串,由匹配此模式的另一子序列或输入序列的结尾终止。数组中子字符串的顺序与其在输入中出现的顺序相同。如果此模式与输入的任何子序列都不匹配,那么得到的数组仅包含一个元素,即字符串形式的输入序列。limit 参数控制应用模式的次数,从而影响结果数组的长度。如果限制 n 大于零,那么模式至多应用 n> – 1 次,数组的长度不大于 n,并且数组的最后条目将包含除最后的匹配定界符之外的所有输入。如果 n 非正,那么将应用模式的次数不受限制,并且数组可以为任意长度。如果 n 为零,那么应用模式的次数不受限制,数组可以为任意长度,并且将丢弃尾部空字符串。

例如,输入 "boo:and:foo" 将产生以下结果及参数:

Regex    

Limit    

Result    

: 2 { "boo", "and:foo" }
: 5 { "boo", "and", "foo" }
: -2 { "boo", "and", "foo" }
o 5 { "b", "", ":and:f", "", "" }
o -2 { "b", "", ":and:f", "", "" }
o 0 { "b", "", ":and:f" }
字段摘要
static int CANON_EQ
启用规范等价。
static int CASE_INSENSITIVE
启用不区分大小写的匹配。
static int COMMENTS
模式中允许空白和注释。
static int DOTALL
启用 dotall 模式。
static int LITERAL
启用模式的字面值解析。
static int MULTILINE
启用多行模式。
static int UNICODE_CASE
启用 Unicode 感知的大小写折叠。
static int UNIX_LINES
启用 Unix 行模式。

 

主要关注下Matcher的方法,列表如下:

Modifier and Type Method and Description
Matcher appendReplacement(StringBuffer sb, String replacement)

Implements a non-terminal append-and-replace step. 参见下面详细的说明
StringBuffer appendTail(StringBuffer sb)

Implements a terminal append-and-replace step. 参见下面详细的说明
int end()

Returns the offset after the last character matched. 返回搜索结果的匹配字符的最后一个字符的位置的后面那个位置,比如“DABCD”中匹配ABC,那么end()的返回值为3+1=4.
int end(int group)

Returns the offset after the last character of the subsequence captured by the given group during the previous match operation.可以参考start(int group)。
boolean find()

Attempts to find the next subsequence of the input sequence that matches the pattern.
boolean find(int start)

Resets this matcher and then attempts to find the next subsequence of the input sequence that matches the pattern, starting at the specified index.
String group()

Returns the input subsequence matched by the previous match.返回上次匹配结果的group(),注意,如果上次匹配没有匹配到,会抛出异常Exception in thread “main” java.lang.IllegalStateException: No match found
at java.util.regex.Matcher.group(Unknown Source)
String group(int group)

Returns the input subsequence captured by the given group during the previous match operation.类似上面,但可以指定group(int group)。注意,如果上次匹配没有匹配到,会抛出异常Exception in thread “main” java.lang.IllegalStateException: No match found
at java.util.regex.Matcher.group(Unknown Source)
String group(String name)

Returns the input subsequence captured by the given named-capturing group during the previous match operation.比如”((A)(B(?<nameC>C)))”,比如matcher.group(“nameC”)则会找到nameC则对应的字符串C。注意,如果上次匹配没有匹配到,会抛出异常Exception in thread “main” java.lang.IllegalStateException: No match found
at java.util.regex.Matcher.group(Unknown Source)
int groupCount()

Returns the number of capturing groups in this matcher’s pattern. 返回group的数量,即左括号的数量,比如”((A)(B(?<nameC>C)))”,那么则对应的groupCount()则为4,注意其中的group=0的不参与计算group数量。任何大于等于0并且小于等于groupCount()的数值,都能保证对应的group(int key)找到一个位置。
boolean hasAnchoringBounds()

Queries the anchoring of region bounds for this matcher.
boolean hasTransparentBounds()

Queries the transparency of region bounds for this matcher.
boolean hitEnd()

Returns true if the end of input was hit by the search engine in the last match operation performed by this matcher.
boolean lookingAt()

Attempts to match the input sequence, starting at the beginning of the region, against the pattern.类似于matches()方法,该方法也会尝试从字符串的开始处开始匹配,但与matches()不同的是,该方法不会要求整个待匹配的字符串和patern完全匹配,而是找到匹配的结果即可。
boolean matches()

Attempts to match the entire region against the pattern. 尝试将整个字符串和pattern匹配。判断pattern是否能够匹配整个字符串。
Pattern pattern()

Returns the pattern that is interpreted by this matcher. 返回Matcher所使用的Pattern。
static String quoteReplacement(String s)

Returns a literal replacement String for the specified String.返回指定 String 的字面值替换 String。 此方法将生成一个 String,它将用作 Matcher 类的 appendReplacement 方法中的字面值替换 s。所产生的 String 将与作为字面值序列的 s 中的字符序列匹配。斜线 (‘\’) 和美元符号 (‘$’) 将不具有任何特殊意义。
Matcher region(int start, int end)

Sets the limits of this matcher’s region. 设置matcher匹配的区域,此方法会调用Matcher的reset()方法,重置搜索结果标志。
int regionEnd()

Reports the end index (exclusive) of this matcher’s region.
int regionStart()

Reports the start index of this matcher’s region.
String replaceAll(String replacement)

Replaces every subsequence of the input sequence that matches the pattern with the given replacement string.
String replaceFirst(String replacement)

Replaces the first subsequence of the input sequence that matches the pattern with the given replacement string.
boolean requireEnd()

Returns true if more input could change a positive match into a negative one.
Matcher reset()

Resets this matcher.重置Matcher所有的状态置为0,包括其中的append position为0.
Matcher reset(CharSequence input)

Resets this matcher with a new input sequence. 类似于reset(),但是会重置搜索查找的字符串。
int start()

Returns the start index of the previous match. 返回上一个搜索结果的起始位置。比如“DABCDEF”中搜索“ABC”那么返回的结果为1.
int start(int group)

Returns the start index of the subsequence captured by the given group during the previous match operation.返回上一个搜索结果的指定group的起始位置。m.start(0)=m.start(),比如“DABCDEF”中搜索“((A(B(C)))”的话,那么start(4),group4对应的为C,那么其实就是搜索字符C对应的位置,也就是4.
MatchResult toMatchResult()

Returns the match state of this matcher as a MatchResult. 返回当前matcher的match state给一个MatchResult。
String toString()

Returns the string representation of this matcher.
Matcher useAnchoringBounds(boolean b)

Sets the anchoring of region bounds for this matcher.
Matcher usePattern(Pattern newPattern)

Changes the Pattern that this Matcher uses to find matches with. 更改当前Matcher使用的Pattern。
Matcher useTransparentBounds(boolean b)

Sets the transparency of region bounds for this matcher.

 

 

  • appendReplacement

    public Matcher appendReplacement(StringBuffer sb,
                            String replacement)
    Implements a non-terminal append-and-replace step.This method performs the following actions:

    1. It reads characters from the input sequence, starting at the append position, and appends them to the given string buffer. It stops after reading the last character preceding the previous match, that is, the character at index start() - 1.该方法会从输入的序列中读取字符,从append position的标志位开始,默认为0,然后追加到StringBuffer当中。当读到上一次匹配之前的最后一个字符的时候,停止,此时指针的位置为start()-1.
    2. It appends the given replacement string to the string buffer.将replacement的字符串追加到StringBuffer当中。
    3. It sets the append position of this matcher to the index of the last character matched, plus one, that is, to end().设置append position为上次匹配到的字符串的end()位置。

    The replacement string may contain references to subsequences captured during the previous match: Each occurrence of ${name} or $g will be replaced by the result of evaluating the corresponding group(name) orgroup(g) respectively. For $g, the first number after the $ is always treated as part of the group reference. Subsequent numbers are incorporated into g if they would form a legal group reference. Only the numerals ‘0’ through ‘9’ are considered as potential components of the group reference. If the second group matched the string "foo", for example, then passing the replacement string "$2bar" would cause "foobar" to be appended to the string buffer. A dollar sign ($) may be included as a literal in the replacement string by preceding it with a backslash (\$).

    Note that backslashes (\) and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string. Dollar signs may be treated as references to captured subsequences as described above, and backslashes are used to escape literal characters in the replacement string.

    This method is intended to be used in a loop together with the appendTail and find methods. The following code, for example, writes one dog two dogs in the yard to the standard-output stream:

     Pattern p = Pattern.compile("cat");
     Matcher m = p.matcher("one cat two cats in the yard");
     StringBuffer sb = new StringBuffer();
     while (m.find()) {
         m.appendReplacement(sb, "dog");
     }
     m.appendTail(sb);
     System.out.println(sb.toString());
    Parameters:
    sb – The target string buffer
    replacement – The replacement string
    Returns:
    This matcher
    Throws:
    IllegalStateException – If no match has yet been attempted, or if the previous match operation failed
    IllegalArgumentException – If the replacement string refers to a named-capturing group that does not exist in the pattern
    IndexOutOfBoundsException – If the replacement string refers to a capturing group that does not exist in the pattern

 

对于正则表达式,还有一个知识点是关于匹配模式的,最常见的是贪婪模式与非贪婪模式,有一篇文章写的很好,连接参考:

http://blog.csdn.net/lxcnn/article/details/4756030

参考文献:

关于Java正则表达式的一些理解

JDK中文版

附录:测试代码

public class GroupStudy {

  public static void main(String[] args) {
    String patternString = "((A)(B(?<nameC>C)))";
    Pattern pattern = Pattern.compile(patternString);
    Matcher matcher = pattern.matcher("DABCDEFABCD");
    System.out.println("First try:");
    if(matcher.find()) {
      System.out.println("Found:" + matcher.pattern().pattern());
    }else {
      System.out.println("Not Found:" + matcher.pattern().pattern());
    }
    
    System.out.println("Next try - matcher.find():");
    if(matcher.find()) {
      System.out.println("Found:" + matcher.pattern().pattern());
    }else {
      System.out.println("Not Found:" + matcher.pattern().pattern());
    }

    //此处应该确保上一次匹配是匹配到的,否则应该在if(matcher.find())之内运行。
    //Group 0 = ABC
    //Group 1 = ABC
    //Group 2 = A
    //Group 3 = BC
    //Group 4 = C
    System.out.println("Group :" + matcher.group());
    System.out.println("Group 0 :" + matcher.group(0));
    System.out.println("Group 1 :" + matcher.group(1));
    System.out.println("Group 2 :" + matcher.group(2));
    System.out.println("Group 3 :" + matcher.group(3));
    System.out.println("Group 4 :" + matcher.group(4));
  
    
    //start()
    System.out.println("start() : " + matcher.start());
    //start(group)
    System.out.println("start(3) : " + matcher.start(4));
    
    //group()
    System.out.println("group() : " + matcher.group());
    //group(4)
    System.out.println("group(4) : " + matcher.group(4));
    //group(nameC)
    System.out.println("group(\"nameC\") : " + matcher.group("nameC"));
    //groupCount()
    System.out.println("groupCount() : " + matcher.groupCount());
    
    
  }
}

运行结果:

First try:
Found:((A)(B(?<nameC>C)))
Next try - matcher.find():
Found:((A)(B(?<nameC>C)))
Group :ABC
Group 0 :ABC
Group 1 :ABC
Group 2 :A
Group 3 :BC
Group 4 :C
start() : 7
start(3) : 9
group() : ABC
group(4) : C
group("nameC") : C
groupCount() : 4

 

About: happyhls


发表评论

电子邮件地址不会被公开。 必填项已用*标注