Python 正则表达式两个字符包含

Python regular expressions two character contain

如何为 python 中至少包含两个字符的字符串编写正则表达式。 1 次。

例如我正在寻找字符 6=:

字符串 1:Test 6 = 正确。
String2:6 test = 正确。
String3:=6 正确。
String4: Test 5 - 8 不正确。
String5: Test 6 不正确。
String6: Test = 不正确。

我尝试了 [6+=+] 但无法正常工作。 谢谢。

我认为正面前瞻可能是您的解决方案。

已测试并正常工作:

(?=.*[6])(?=.*[=]).*

我已经在 regex101.com 上试过了,您在测试正则表达式时可能也会发现它很有用。

如果您要查找字符串中任意位置的两个字符。你可能不需要重新。

for item in ['6', '=']:
   found = string_to_search.count(item)
   # item must be present
   if not found:
      # handle bad data
   # make sure there is only one match
   if found > 1:
      # handle bad data

一般来说,使用正则表达式比使用字符串操作慢。我认为您可以使用这样的方法更有效地解决您的问题:

>>> a
'test 6 ='
>>> [idx for idx, ch in enumerate(a) if ch == '6' or ch == '=']
[5, 7]