背景

这个语法不常用,用的时候每次都记不住。
写下来,背过!

捕获组和反向引用(Capturing Group & Backreference)

1 匹配 pattern 并自动设置组号

  1. (pattern)

2 匹配 pattern 并将组名设置为 name

(?<name>pattern)
(?'name'pattern)

3 使用组号 num 反向引用

反向引用指被匹配成功的前序组再次出现,下同。

\num

例如:

  • text = abc123abc,abc123bca
  • pattern = (\w)(\w)\w\d+\1\2\w
  • result = abc123abc

    4 使用组名 name 反向引用

    \k<name>
    \k'name'
    
    注意:部分语言不支持此种反向引用方式。

非捕获组(Non-capturing Group)

非捕获的 pattern 片段,会参与匹配查询,但不出现在最终的捕获结果中,也不会被分配组号。

1 普通非捕获组

匹配 pattern 但不捕获。

(?:pattern)

注意:这个语法没有出现在 RegularExpression.info 的说明中,可能是野鸡语法。

2 零宽度正向预查(Positive Lookahead)

// 这尼玛什么™鬼的烂中文翻译!!!下同。
谁后面是 pattern,就捕获谁;叫“是后缀捕获”不好么?
人话版本:“后缀是这个,就捕获本体”,英文说明更好理解。

Matches at a position where the pattern inside the lookahead can be matched. Matches only the position. It does not consume any characters or expand the match. Syntax

(?=pattern)

例如:

  • text = 1verygood,2verybad
  • pattern = \dvery(?=good)
  • result = 1very

    3 零宽度负向预查(Negative Lookahead)

    谁后面不是 pattern,就捕获谁;叫“非后缀捕获”不好么?
    人话版本:“后缀不是这个,就捕获本体。”

    Similar to positive lookahead, except that negative lookahead only succeeds if the regex inside the lookahead fails to match.

(?!pattern)
(?!pattern)

例如:

  • text = 1verygood,2verybad
  • pattern = \dvery(?!good)
  • result = 2very

    4 零宽度正向回查(Positive Lookbehind)

    谁前面是 pattern,就捕获谁;叫“是前缀捕获”不好么?
    人话版本:“前缀是这个,就捕获本体。”

    Matches at a position if the pattern inside the lookbehind can be matched ending at that position.

(?<=pattern)

例如:

  • text = goodguy1,badguy2
  • pattern = (?<=good)guy\d
  • result = guy1

    5 零宽度反向回查(Negative Lookbehind)

    谁前面不是 pattern,就捕获谁;叫“非前缀捕获”不好么?
    人话版本:“前缀不是这个,就捕获本体。”

    Matches at a position if the pattern inside the lookbehind cannot be matched ending at that position.

(?<!pattern)

例如:

  • text = goodguy1,goodguy2
  • pattern = (?<!good)guy\d
  • result = guy2

    6 Lookaround Conditional

    太复杂了,没研究。

注释(Comment)

添加内容为 comment 的注释。

(?#comment)

Reference