Python正则表达式搜索出现不需要的字符

2024-10-01 04:53:42 发布

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

在下面的python代码中

import re

myText = "The color of the car is red. Which is a popular color."
regularExp = "The color of the car is\s*(?P<color>\w*)..*"
pattern = re.compile(regularExp)

match = re.search(pattern, myText)
color = match.groups("color")
print(color)

我希望输出是red。但我得到的是('red',)。我做错什么了


Tags: ofthe代码importrewhichismatch
3条回答

re.search返回一个match object,正如您所看到的groups方法总是返回一个元组。因此,要么访问结果color[0]的第一个元素,要么改用group函数:

color = match.group("color")

另请注意,match.groups("color")可能并不像您认为的那样,引用文档:

match.groups(default=None)

The default argument is used for groups that did not participate in the match; it defaults to None.

这意味着您将设置颜色为“颜色”如果没有找到匹配您的颜色组

对于match对象mm.groups返回一个tuple,一个不可变的序列。你可以索引它或者

color = m.group(1) # m.group(n) for nth group

或者

color = m.group('color') # for named group

你说('red',)含有不需要的字符。这可能意味着您需要重新学习基本的python,因为您无法识别tuple

打印的是元组,而不是字符串。请尝试以下操作:

print(color[0])

或(信用证:Wiktor Stribi)ż电子战):

color = match.group("color")
print(color)

相关问题 更多 >