每當任務(對于patternStart.finditer(TestString) 中的匹配)未找到匹配項時,我都會嘗試打?。ㄎ凑业狡ヅ漤棧N乙恢眻猿诌@個沒有任何成功。任何意見,將不勝感激。字符串“jeke”故意不包含數字,因此找不到匹配項。TestString = 'jeke'patternStart = re.compile(r'\d')cnt = 0 # Initialize the counterwanted1 = [1] # Defines the 1-based IDs of the matches you want to displaywanted2 = [2] # Defines the 1-based IDs of the matches you want to displayfor match in patternStart.finditer(TestString): cnt += 1 if cnt in wanted1: out = match.group() else: print('match was not found')我已經嘗試過了。if match.group() is None: print('match was not found')if out is None: print('match was not found')
1 回答

鳳凰求蠱
TA貢獻1825條經驗 獲得超4個贊
您可以使用cnt來確定是否找到任何匹配項:
for match in patternStart.finditer(TestString):
cnt += 1
if cnt in wanted1:
out = match.group()
if cnt == 0:
print('match was not found')
或者使用單獨的found_match變量:
found_match = False
for match in patternStart.finditer(TestString):
found_match = True
cnt += 1
if cnt in wanted1:
out = match.group()
if not found_match:
print('match was not found')
添加回答
舉報
0/150
提交
取消