【发布时间】:2019-03-01 04:50:31
【问题描述】:
我有 str ,我想在单引号内获取子字符串 ('):
line = "This is a 'car' which has a 'person' in it!"
所以我用了:
name = re.findall("\'(.+?)\'", line)
print(name[0])
print(name[1])
汽车
人
但是当我尝试这种方法时:
pattern = re.compile("\'(.+?)\'")
matches = re.search(pattern, line)
print(matches.group(0))
print(matches.group(1))
# print(matches.group(2)) # <- this produces an error of course
“汽车”
汽车
所以,我的问题是为什么模式在每种情况下的行为都不同?我知道前者返回“字符串中模式的所有非重叠匹配”,而后者匹配对象可能会解释一些差异,但我希望使用相同的模式相同的结果(即使格式不同)。
所以,为了更具体:
- 在
findall的第一种情况下,模式返回所有子字符串,但在后一种情况下,它只返回第一个子字符串。 - 在后一种情况下,
matches.group(0)(对应于文档中的the whole match)不同于matches.group(1)(对应于第一个带括号的子组)。这是为什么呢?
re.finditer("\'(.+?)\'", line) 返回匹配对象,因此它的功能类似于re.search。
【问题讨论】:
-
你至少明白
re.search只找到第一个匹配项吗? -
根据manual:扫描字符串,寻找正则表达式模式产生匹配的第一个位置
-
re.group(0) 指的是超群。
-
另外
finditer应该在循环中使用。