命名分组(?<name>...)
捕获组 capture group
- 普通捕获组 (expression)
- 命名捕获组(?expression)
普通捕获组
从正则表达式左侧开始,每出现一个左括号"(",就记作一个分组,分组编号从1开始. 0代表整个表达式.
对于时间字符串: 2020-11-06, 表达式如下
(\d{4})-((\d{2})-(\d{2}))
有4个左括号,所以有4个分组:
编号 | 捕获组 | 匹配 |
0 | (\d{4})-((\d{2})-(\d{2})) | 2020-11-06 |
1 | (\d{4}) | 2020 |
2 | ((\d{2})-(\d{2})) | 11-06 |
3 | (\d{2}) | 11 |
4 | (\d{2}) | 06 |
命名捕获组
每组以左括号开始的捕获组,都紧跟?, 而后才是正则表达式.
对于时间字符串: 2020-11-06, 表达式如下:
(?<year>\d{4})-(?<md>(?<month>\d{2})-(?<day>\d{2}))
有4个命名捕获组, 分别是:
编号 | 名称 | 捕获组 | 匹配 |
0 | 0 | (?<year>\d{4})-(?<md>(?<month>\d{2})-(?<day>\d{2})) | 2020-11-06 |
1 | year | (?<year>\d{4}) | 2020 |
2 | md |
(?<md>(?<month>\d{2})-(?<day>\d{2})) |
11-06 |
3 | month | (?<month>\d{2}) | 11 |
4 | day | (?<day>\d{2}) | 06 |