在python的regex模块中,`.*`的含义我认为它意味着任何东西?

2024-07-01 07:10:30 发布

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

我身上发生了一些奇怪的事。很长一段时间以来,我一直认为.*意味着任何字符的任何数量,包括任何字符。我举了两个例子,给出了不同的结果:

例1

此示例按我的预期打印:

string_2 = 'SomethingStuff stuff1 ' 
my_regex = '(stuff)'
match_object = re.findall(my_regex, string_2, flags=re.I)
print match_object

输出:

['Stuff', 'stuff']

例2

这个示例应该打印相同的内容,正如我目前所理解的.*,但是它没有:

string_2 = 'SomethingStuff stuff1 '
my_regex = '(stuff).*'    # notice the difference here
match_object = re.findall(my_regex, string_2, flags=re.I)
print match_object

输出:

['Stuff']

为什么这些不同?我真的很烦


Tags: re示例stringobjectmymatch字符regex
2条回答

由于您在regex中使用的捕获组(...)re.findall应该打印与捕获组中存在的模式匹配的字符。请注意,re.findall应该首先优先选择组,然后是匹配项。由于regex中的Stuff存在于组中,并且下面的.*匹配所有字符直到最后一个(它包括第二个stuff),所以regex应该只打印第一个Stuff。如果删除组,它应该打印从第一个stuff到最后一个的所有chracaters

>>> string_2 = 'SomethingStuff stuff1 '
>>> re.findall('stuff.*', string_2, flags=re.I)
['Stuff stuff1 ']

问题在于.*:它匹配所有内容,它将继续使用字符串,直到什么都没有了。如果希望它停止并且不消耗下一个'stuff',请使用问号表示非贪婪匹配:

>>> string_2 = 'SomethingStuff stuff1 '
>>> my_regex = '(stuff).*'    # notice the difference here
>>> match_object = re.findall(my_regex, string_2, flags=re.I)
>>> print (match_object)
['Stuff']
>>> my_regex = '(stuff).*?'    # notice the difference here
>>> match_object = re.findall(my_regex, string_2, flags=re.I)
>>> print (match_object)
['Stuff', 'stuff']

相关问题 更多 >

    热门问题