Skip to main content
 首页 » 编程设计

python之正则表达式,更好的方法

2024年08月23日33tintown

如果定界符在字符串中,如何分隔可能在字符串中多次匹配的正则表达式,即: 那么'Bang bang swing'(BBS) aota 'Bing Bong Bin'(BBB)

使用正则表达式:"'.+'(\S+)" 它将匹配来自 'Bang ... (BBB) 的所有内容,而不是匹配 'Bang bang swing'(BBS) 和 'Bing Bong Bin'(BBB)

我有一种使用正则表达式的方式:'[A-z0-9-/?|q~`!@#$%^&*()_-=+ ]+'(\S+) 但这太过分了,老实说,我什至讨厌它能正常工作。 我对正则表达式相当陌生,从 Python 的实现开始显然不是启动它的最明智的方式。

请您参考如下方法:

要获取从一个字符到另一个字符的子字符串,中间不能出现,您应该始终考虑使用 negated character classes .

The [negated] character class matches any character that is not in the character class. Unlike the dot, negated character classes also match (invisible) line break characters. If you don't want a negated character class to match line breaks, you need to include the line break characters in the class. [^0-9\r\n] matches any character that is not a digit or a line break.

所以,你可以使用

'[^']*'\([^()]*\) 

参见 regex demo

这里,

  • '[^']*' - 匹配 ' 后跟除 ' 之外的 0 个或多个字符,然后是 >' 再一次
  • \( - 匹配文字 )(必须转义)
  • [^()]* - 匹配除 ( 和 ) 之外的 0 个或多个字符(它们不必在内部进行转义一个字符类)
  • \) - 匹配文字 )(必须在字符类之外进行转义)。

如果您在 (...) 部分之前可能有 1 个或多个单引号,您将需要一个展开的惰性匹配正则表达式:

'[^']*(?:'(?!\([^()]*\))[^']*)*'\([^()]*\) 

参见 regex demo .

在这里,'[^']*(?:'(?!\([^()]*\))[^']*)*' 与'.*?' 带有 DOTALL 标志,但由于线性正则表达式执行效率更高。参见 more about unrolling regex technique here .

编辑:

当输入字符串既不复杂又不短时,惰性点匹配会更有效率。但是,当复杂性增加时,惰性点匹配可能会导致问题。