当字符串与正则表达式匹配时,我想记住它的一部分,例如:
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中,我们只需要说partment=$1)
有人有主意吗?在
即使在Perl中也不能这样做。实际上,您需要对字符串运行regex搜索来初始化
$1
变量。在在Python中,首先将其与
re.search
匹配,然后您将能够访问match data对象:参见Python demo
相关问题 更多 >
编程相关推荐