如何在匹配正则表达式时记住字符串的一部分?

时间:2016-04-13 09:52:05

标签: python regex

我想记住字符串的一部分,当它匹配正则表达式时:

for line in my file:
    regex = re.compile(r'characters(textToSave)otherCharacters')
    # here I would like to memorise what's in parenthesis like somehow
    # portion = /1 (texToSave)
    # so then I could do:
    if regex.search(line):
       #do something with portion

(以perl为例,我们只需说部分= $ 1)

有人有想法吗?

1 个答案:

答案 0 :(得分:0)

即使在Perl中也不能这样做。您需要对字符串实际运行正则表达式搜索以初始化$1变量。

在Python中,首先,将其与re.search匹配,然后您就可以访问匹配数据对象了:

import re
line = "characterstextToSaveotherCharacters"
regex = re.compile(r'characters(textToSave)otherCharacters')
matchObj = regex.search(line)
if matchObj:
    print(matchObj.group(1)) # Now, matchObj.group(1) contains textToSave

请参阅Python demo