Skip to main content
 首页 » 编程设计

python之PCRE 正则表达式 (*COMMIT) 等效于 Python

2024年10月17日36shangdawei

下面的模式花了我很长时间才找到。当我终于找到它时,发现它在 Python 中不起作用。有谁知道是否有替代方案?

(*COMMIT) 定义:如果模式的其余部分不匹配,则导致整个匹配完全失败。

(*FAIL) 在 Python 中也不起作用。但这可以用 (?!) 代替。

+-----------------------------------------------+ 
|Pattern:                                       | 
|^.*park(*COMMIT)(*FAIL)|dog                    | 
+-------------------------------------+---------+ 
|Subject                              | Matches | 
+-----------------------------------------------+ 
|The dog and the man play in the park.|  FALSE  | 
|Man I love that dog!                 |  TRUE   | 
|I'm dog tired                        |  TRUE   | 
|The dog park is no place for man.    |  FALSE  | 
|park next to this dog's man.         |  FALSE  | 
+-------------------------------------+---------+ 

示例取自: regex match substring unless another substring matches

请您参考如下方法:

这可能不是通用的替代品,但对于您的情况,您可以使用前瞻,断言 dog 匹配,但 park 不匹配:^(?=.*dog)(?!.*park ).*$

您在 regex101 上的 sample