Skip to main content
 首页 » 编程设计

python之贪婪的正则表达式或逻辑

2024年08月20日35jirigala

考虑字符串 'X Y Z' 和替换

re.sub('Y|Y Z', '', 'X Y Z') 

返回

'X  Z' 

当它也可以返回 'X ' 时。显然,它首先匹配、替换,然后另一个替代项的模式不再匹配。

有没有办法告诉替换更喜欢最长的替换?

请您参考如下方法:

根据 Python re documentation - Regular Expression Syntax, | part ,

A|B, where A and B can be arbitrary REs, creates a regular expression that will match either A or B. An arbitrary number of REs can be separated by the '|' in this way. This can be used inside groups (see below) as well. As the target string is scanned, REs separated by '|' are tried from left to right. When one pattern completely matches, that branch is accepted. This means that once A matches, B will not be tested further, even if it would produce a longer overall match. In other words, the '|' operator is never greedy. To match a literal '|', use \|, or enclose it inside a character class, as in [|].

将最长的模式放在较短的模式之前:

>>> re.sub('Y Z|Y', '', 'X Y Z') 
'X '