当字符串的一部分与正则表达式匹配时,如何记忆它?

2024-09-30 14:28:45 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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)

有人有主意吗?在


Tags: 字符串inreformylinedoregex
1条回答
网友
1楼 · 发布于 2024-09-30 14:28:45

即使在Perl中也不能这样做。实际上,您需要对字符串运行regex搜索来初始化$1变量。在

在Python中,首先将其与re.search匹配,然后您将能够访问match data对象:

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

相关问题 更多 >