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



如何在python中为字符串编写正则表达式,该字符串至少包含1x时间的两个字符。

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

字符串 1:Test 6 =是正确的。
字符串 2:6 test =是正确的。
字符串 3:=6是正确的。
字符串 4:Test 5 - 8不正确。
字符串5:Test 6不正确。
字符串 6: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]

相关内容

最新更新