当提供像 0[0-9] 这样的输入时,有人可以告诉我 matches.group(1) 是什么吗?它不是 None 也不是 (换行)但它是一个 str [关闭]

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

我正在做一个关于 ipv4 验证器的正则表达式的问题,我知道关于它的正则表达式已经存在,而且我知道我的 ip 验证方法不是最好的,但如果我输入像“00”,01'这样的输入,'02'...'09' 我不知道 matches.group(1) 是什么。所以我什至不能在条件中使用它。

import re
innput=input('three digit number: ')
matches=re.search(r'^([1-2]?)([0-9]?)([0-9])$',innput)
print(matches.group(1))
print(matches.group(2))
print(matches.group(3))
print(type(matches.group(1)))
if matches.group(1)==None or matches.group(1)=='\n':
    print('ok expected')
else:
    print('matches.group(1) is not None and is not a newline but it is a str')
python regex variables regex-group python-re
1个回答
0
投票

matches.group(1)
是与正则表达式中的第一个捕获组匹配的输入部分。第一个捕获组是
([1-2]?)
,它与输入字符串开头的可选
1
2
匹配。因此,如果字符串以
1
2
开头,则为该字符串,否则为空字符串。

因此,当您输入的是像

09
这样的数字时,第一个捕获组为空,并且
matches.group(1)
是一个空字符串。

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