测试非空分组捕获

1 投票
1 回答
2531 浏览
提问于 2025-04-18 05:56

这是一个初学者的Python问题。

我想学习一些简单的Python语法,用来测试非空的分组捕获。

例子不重要,我想学的是如何查看非空的捕获。

我试过这个:

subj = 'abc123 bbb22 cc'
rgx = re.compile(r'[a-z]+(\d+)?')
for match in re.finditer(rgx,subj):
    print (match.group(1))

这段代码给出了和非空的第一个分组:123,22,None

好的,从这里开始,你能教我怎么做:

  • 计算非空的第一个分组捕获
  • 只打印非空的第一个分组捕获

谢谢你!

1 个回答

3

你可以通过使用 if match 来检查这个匹配是否为空:

subj = 'abc123 bbb22 cc'
rgx = re.compile(r'[a-z]+(\d+)?')
for match in re.finditer(rgx,subj):
    if match.group(1):
        print (match.group(1))

另外,你也可以这样做:

subj = 'abc123 bbb22 cc'
rgx = re.compile(r'[a-z]+(\d+)?')
result = [i for i in re.findall(rgx, subj) if i]
for match in result:
    print (match)

撰写回答