使用正则表达式捕获方括号内的文本 [英] Capture the text inside square brackets using a regex
本文介绍了使用正则表达式捕获方括号内的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在这里看到了问题:正则表达式捕获{}这与我想要的类似,但我无法让它工作.
I saw question here: Regex to capture {} which is similar to what I want, but I cannot get it to work.
我的数据是:
[Honda] Japanese manufacturer [VTEC] Name of electronic lift control
我希望输出是
[Honda], [VTEC]
我的表达是:
m = re.match('(\[[^\[\]]*\])', '[Honda] Japanese manufacturer [VTEC] Name of electronic lift control')
我希望:
m.group(0)
输出[Honda]
m.group(1)
输出[VTEC]
m.group(0)
to output[Honda]
m.group(1)
to output[VTEC]
然而两者都输出[Honda]
.如何访问第二场比赛?
However both output [Honda]
. How can I access the second match?
推荐答案
您可以使用 re.findall
来获取所有匹配项,尽管您会在列表中获取它们,但您不会'不需要捕获组:
You can use re.findall
to get all the matches, though you'll get them in a list, and you don't need capture groups:
m = re.findall('\[[^\[\]]*\]', '[Honda] Japanese manufacturer [VTEC] Name of electronic lift control')
给出 ['[Honda]', '[VTEC]']
所以你可以得到每一个:
Gives ['[Honda]', '[VTEC]']
so you can get each with:
print(m[0])
# => [Honda]
print(m[1])
# => [VTEC]
这篇关于使用正则表达式捕获方括号内的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文