I'm trying out one simple regex pattern. But it's behaving strange.
我正在尝试一个简单的regex模式。但它的奇怪的行为。
re.findall('ABC\-\d{2}\-\d{3,5}(\[[A-Z]\])?', 'ABC-01-1234[Z],ABC-12-5678')
The output is always:
输出总是:
['[Z]']
whereas I want both the strings i.e. ABC-01-1234[Z],ABC-12-5678
as my matched pattern. [Z]
is optional. Don't know why ?
is not working correctly.
而我想要两个字符串即ABC-01-1234[Z] ABC-12-5678作为我的匹配模式。[Z]是可选的。不知道为什么?不正常工作。
1 个解决方案
#1
3
Change your regex to:
改变你的正则表达式:
re.findall('(ABC\-\d{2}\-\d{3,5}(?:\[[A-Z]\])?)', 'ABC-01-1234[Z],ABC-12-5678')
Group around the whole match (...)
. And non capturing group around your maybe match (?:...)
在整个比赛中分组(…)。和非捕获组围绕你的可能匹配(?:…)
Tested in JS (not sure if will work in Python):
在JS中测试(不确定是否在Python中工作):
'ABC-01-1234[Z],ABC-12-5678'.match(/(ABC\-\d{2}\-\d{3,5}(?:\[[A-Z]\])?)/g); // ["ABC-01-1234[Z]", "ABC-12-5678"]
#1
3
Change your regex to:
改变你的正则表达式:
re.findall('(ABC\-\d{2}\-\d{3,5}(?:\[[A-Z]\])?)', 'ABC-01-1234[Z],ABC-12-5678')
Group around the whole match (...)
. And non capturing group around your maybe match (?:...)
在整个比赛中分组(…)。和非捕获组围绕你的可能匹配(?:…)
Tested in JS (not sure if will work in Python):
在JS中测试(不确定是否在Python中工作):
'ABC-01-1234[Z],ABC-12-5678'.match(/(ABC\-\d{2}\-\d{3,5}(?:\[[A-Z]\])?)/g); // ["ABC-01-1234[Z]", "ABC-12-5678"]