python - 每当任务(patternstart.finditer 中的匹配)返回 None 时,我如何创建操作?
问题描述
每当任务(对于 patternStart.finditer(TestString) 中的匹配项)找不到匹配项时,我都会尝试打印(未找到匹配项)。我一直坚持这一点,没有任何成功。任何意见,将不胜感激。
字符串 'jeke' 故意不包含数字,因此找不到匹配项。
TestString = 'jeke'
patternStart = re.compile(r'\d')
cnt = 0 # Initialize the counter
wanted1 = [1] # Defines the 1-based IDs of the matches you want to display
wanted2 = [2] # Defines the 1-based IDs of the matches you want to display
for 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')
解决方案
您可以使用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')
推荐阅读
- php - 使 Laravel 8 slug 变量不区分大小写
- business-objects - SAP BO 发布以前运行良好,而发布没有改变,怎么会失败?
- mysql - How to order result according to another table in mysql
- r - 有没有一种方法可以使用 lattice 包函数 bwplot() 重现箱线图
- android - 从图层列表项中删除填充
- php - 将数据和图像文件保存到数据库 Laravel 中失败
- java - spring-data-elasticsearch 自定义日期格式错误
- firebase-authentication - 下一个js和firebase认证登录页面问题
- excel - 表示的枢轴
- json - 无法使用 getJSON 从卡片反人类 API 中获取数据