如果我在正则表达式中包含空格,那么会有什么不同

时间:2021-11-16 21:21:14
import re

line = "Cats are smarter than dogs"

matchObj = re.match( r'(.*) are (.*)', line)

if matchObj:

    print ("matchObj.group(2) : ", matchObj.group(2))
else:

    print ("No match!!")

When i run this code i get an ouput: smarter than dogs

当我运行这个代码时,我得到了一个输出:比狗更聪明

But if put an extra space at the end of my my RE

但如果在我的RE的末尾增加一个额外的空间

matchObj = re.match( r'(.*) are (.*) ', line)

I get output as: smarter than

我输出的结果是:比。更聪明

Can anyone explain why am i getting this difference in output

任何人都可以解释为什么我在输出中得到这个差异

1 个解决方案

#1


0  

When you're adding the extra space in matchObj = re.match( r'(.*) are (.*) ', line), you're asking to match as many character as it can in (.*) followed by a space.

当你在matchObj = re.match(r'(。*)是(。*)',line)中添加额外空格时,你要求在(。*)中匹配尽可能多的字符,然后空间。

In this case it is smarter than, as the space character matches the space in dogs.

在这种情况下,它比空间角色与狗的空间相匹配更聪明。

Without the space, the . can match any number of characters other than new line. So it ends up matching until the end of the string, smarter than dogs.

没有空间,。可以匹配除新行之外的任意数量的字符。因此它最终匹配直到字符串结束,比狗更聪明。

Read the documentation on regex for more info.

阅读有关正则表达式的文档以获取更多信息。

#1


0  

When you're adding the extra space in matchObj = re.match( r'(.*) are (.*) ', line), you're asking to match as many character as it can in (.*) followed by a space.

当你在matchObj = re.match(r'(。*)是(。*)',line)中添加额外空格时,你要求在(。*)中匹配尽可能多的字符,然后空间。

In this case it is smarter than, as the space character matches the space in dogs.

在这种情况下,它比空间角色与狗的空间相匹配更聪明。

Without the space, the . can match any number of characters other than new line. So it ends up matching until the end of the string, smarter than dogs.

没有空间,。可以匹配除新行之外的任意数量的字符。因此它最终匹配直到字符串结束,比狗更聪明。

Read the documentation on regex for more info.

阅读有关正则表达式的文档以获取更多信息。