Files
rikako-note/regular expression/正则进阶语法.md
2024-03-10 22:54:03 +08:00

93 lines
3.5 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 正则表达式
## 语法
### No Capturing Group `(?:regex)`
如果不想要正则表达式中的group捕获其匹配可以通过在group的左`(`符号后指定`?:`其会将group设置为非捕获匹配。
```bash
# 使用示例如下
color=(?:red|green|blue)
```
### Named Caputure Group `(?<name>regex)`
在java中支持named group机制从而可使用name来获取识捕获的匹配。其可以避免在复杂表达式中通过下表进行匹配时带来的复杂解析问题。
使用语法为`(?<name>regex)`,使用示例如下所示:
```bash
[Ww]indows(?<versionTag>95|98|7|8|10|11)
```
```java
public static void testRegex() {
Pattern pattern = Pattern.compile("[Ww]indows(?<versionTag>95|98|7|8|10|11)");
Matcher matcher = pattern.matcher("I use windows11 Operating System...");
if(matcher.find()) {
String versionTag = matcher.group("versionTag");
System.out.printf("windows version used is %s%n", versionTag);
} else {
System.out.println("I don't use Windows System");
}
}
```
### Atomic Grouping `(?>regex)`
在正则表达式中,支持通过`(?>regex)`的语法来指atomic grouping。当指定匹配为atomic grouping后例如`a(?>bc|b)c`其会匹配abcc但是不会匹配abc。
因为当一个group被指定atomic grouping后一旦该group成功匹配过一次那么其会丢弃group中token记录的backtracking position不会再尝试group中指定的其他匹配。例如在匹配abc时`(?>bc|b)`表达式和`bc`匹配成功后atomic grouping即会丢弃回溯位置后续regex的末尾`c`字符无法匹配,即会导致整个匹配失败,而不会回溯后重新匹配`(?>bc|b)`中的`b`
使用示例如下所示:
```bash
# 其会匹配abcc但是不会匹配abc
a(?>bc|b)c
```
### Negative Lookahead `(?!regex)`
通过negative Lookahead语法可以指定`后面不被...跟随`的正则表达式。例如,`q(?!u)`,其会匹配`aqe`字符串中的`q`
注意,`q[^u]`是无法表示和`q(?!u)`一样的效果的,因为`q(?!u)`匹配的是`aqe`字符串中的`q`,而`q[^u]`匹配的则是`aqe`字符串中的`qe`
并且,**Negative Lookahead是No Caputure Group**。
使用示例如下所示:
```bash
# 其会匹配aqe字符串中的q
q(?!u)
```
### Positive Lookahead `(?=regex)`
通过positive lookahead的语法则是可以指定`后面被...跟随`的正则表达式,例如`q(?=u)`。但是,`u并不会成为该regex匹配的一部分。`
并且,**Negative Lookahead是No Caputure Group**。
使用示例如下所示:
```bash
# 匹配后缀有u的q例如aqua中的q
q(?=u)
```
> 如果想要捕获Lookahead中的匹配内容可以使用`(?=(regex))`的语法。
### Negative Lookbehind `(?<!regex)`
Negative Lookbehind和Negative Lookahead类似但是是针对前缀做断言。其会告诉regex引擎暂时性后退一步检测lookbehind中指定的regex是否可以匹配。
该语法匹配`前面不由...前缀`的正则表达式。
`(?<!a)b`正则表达式,则是可以匹配`b``debt`中的`b`,但是匹配不了`cab`中的`b`
使用示例:
```bash
(?<!a)b
```
### Positive Lookbehind `(?<=regex)
该语法匹配`前面由...前缀`的正则表达式。
`(?<=a)b`可以匹配`cab`中的`b`,但是无法匹配`b``debt`中的b。
使用示例:
```bash
(?<=a)b
```
### 不包含某表达式的语法
如果想要通过正则来表达`不包含...`的语法,可以通过`^((?!regex).)*$`来表示。