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

2024-04-23 18:57:22 发布

您现在位置:Python中文网/ 问答频道 /正文

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

例如,我要查找字符6=

字符串1:Test 6 =正确。
字符串2:6 test =正确。
字符串3:=6正确。
字符串4:Test 5 - 8不正确。
字符串5:Test 6不正确。
字符串6:Test =不正确。

我试过[6+=+],但工作不正常。 谢谢


Tags: 字符串test字符
3条回答

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

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

如果要在字符串中的任意位置查找两个字符。你可能不需要一个re

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

我认为积极的前瞻可能是你的解决方案

测试和工作:

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

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

相关问题 更多 >