美文网首页
【The Java™ Tutorials】【Regular Ex

【The Java™ Tutorials】【Regular Ex

作者: Ppian | 来源:发表于2018-03-23 16:22 被阅读0次

    编号

    正则表达式((A)(B(C)))中有4个capturing group,它们分别是:

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

    编号其实很简单,从左向右找左括号就行。调用Matcher对象中的groupCount方法会返回该正则表达中capturing group的数量。

    其实还有一个特殊的group,group 0,它表示整个正则表达式,它不被groupCount计算在内。

    知道group的编号是很重要的,因为Matcher中很多方法接收group编号作为形参,比如:

    • public int start(int group): Returns the start index of the subsequence captured by the given group during the previous match operation.
    • public int end (int group): Returns the index of the last character, plus one, of the subsequence captured by the given group during the previous match operation.
    • public String group (int group): Returns the input subsequence captured by the given group during the previous match operation.

    比如我们的正则表示是(面积:)(\d)+,我们想得到面积是多少:


    (面积:)(\d)+

    但是这个正则表达匹配到的是“面积:123”,但是我们只想要“123”这个数字,这个时候我们就可以通过调用group(2)来直接得到这个数字。

    反向引用(backreference)

    我们先来看一个场景,再来解释什么是反向引用。我们想匹配像1212,2323这样数字,即第一位和第三位一样,第二位和第四位一样。用我们前面学的知识好像没法解决。这个时候反向引用就派上用场了:

    The section of the input string matching the capturing group(s) is saved in memory for later recall via backreference. A backreference is specified in the regular expression as a backslash (\) followed by a digit indicating the number of the group to be recalled.

    我们来看一下如何用反向应用解决我们的问题:


    反向引用

    其中\1就表示group 1匹配到的内容。

    相关文章

      网友评论

          本文标题:【The Java™ Tutorials】【Regular Ex

          本文链接:https://www.haomeiwen.com/subject/moyqixtx.html