如何在 Python 正则表达式中至少搜索两个组中的一个,同时还要寻找必须的第三组?

How to search for at least one of two groups in Python Regex, when also looking for a third group that is a must?

我正在尝试使用正则表达式来查找程序中误用的运算符。

具体来说,我试图找出某些运算符(例如 %、$ 和 @)是否在两侧没有数字的情况下被使用。

这里有一些误用的例子:

'5%'
'%5'
'5%+3'
'5%%'

有没有办法只用一个 re.search 就可以做到这一点?

我知道我可以使用 + 至少表示一个,或者 * 至少表示零, 但看着:

([^\d]*)(%)([^\d]\*)

我想找到至少存在 group(1) 和 group(3) 之一的情况,
因为在其两边插入带有数字的 % 是该运算符的一个很好的用途。

我知道我可以使用:

match = re.search(r'[^\d\.]+[@$%]', user_request)
if match: 
    return 'Illegal use of match.group()'

match = re.search(r'[@$%][^\d\.]+', user_request)
if match: 
    return 'Illegal use of match.group()'

但我更愿意使用单个 re.search 行。

还有 - 当我使用 [^\d.] 时,这是否包括字符串的开头和结尾?或者只有不同的字符?

谢谢:)

您可以使用带有负向前瞻和负向后向的 alternation 来断言之前和之后的不是数字:

(?<!\d)[@$%]|[@$%](?!\d)

将匹配:

  • (?<!\d) 负后视检查左边的不是数字
  • [@$%] 字符 class,匹配 @$%
  • 之一
  • |
  • [@$%] 字符 class,匹配 @$%
  • 之一
  • (?!\d) 负前瞻检查右边的不是数字

例如:

match = re.search(r'(?<!\d)[@$%]|[@$%](?!\d)', user_request)
if match: 
    return 'Illegal use of match.group()'

Regex demo | Python demo

[^\d.] 不匹配数字或文字点。 character class 中的 ^ 否定它包含的内容。但如果字符串的第一个字符不是数字或点,那么它将匹配。