Python - 句子中的 2 组字母数字表达式

问题描述 投票:0回答:2

如何解决以下问题?为什么我的搜索没有给我正确的输出?enter image description here

请在下面找到我的代码,即re.search代码:

import re
def check_character_groups(text):
  result = re.search(r"^\w \w", text)
  return result != None

print(check_character_groups("One")) # False
print(check_character_groups("123  Ready Set GO")) # True
print(check_character_groups("username user_01")) # True
print(check_character_groups("shopping_list: milk, bread, eggs.")) # False

有人可以帮助我吗?

非常感谢您的帮助。

问候, 亚历山德拉

这是我的代码enter image description here

python search expression
2个回答
0
投票

在 2 个 \w 语句之间插入 \s+,如下所示:“\w\s+\w”

\s+ 查找中间的一个或多个空格。


0
投票

如果您想要恰好两个这样的组。

import re
def check_character_groups(text):
  result = re.findall(r"\w+|\d+", text)

  return len(result) == 2

如果你想要 2 个或更多,只需将 return len(result) == 2 更改为 return len(result) >= 2

© www.soinside.com 2019 - 2024. All rights reserved.