正则表达式正向前瞻仍包括结果中的表达式

2024-05-15 16:17:12 发布

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

这是我的正则表达式

'(?<=1\)).*'

我正在努力匹配

A good strategy is a set of actions that enables a firm to achieve its own internal goals without regard to the external environment.

但它不断返回1),我不希望它像这样

1) A good strategy is a set of actions that enables a firm to achieve its own internal goals without regard to the external environment.

我如何只回答这个问题

编辑:由于我的错误无法复制,我正在共享完整的代码

searchCounter = 1

bookDict = {}

with open ('StratMasterKey.txt', 'rt') as myfile:

for line in myfile:
    question_pattern = re.compile((rf'(?<={searchCounter}\)).*'), re.IGNORECASE)
    if question_pattern.search(line) != None: 

        bookDict[searchCounter] = line 
        searchCounter +=1

Tags: oftoactionsthatislineitsgood
1条回答
网友
1楼 · 发布于 2024-05-15 16:17:12

你的正则表达式很好,并且匹配正确的东西。问题是,在测试匹配后,使用原始行而不是匹配部分。改为这样做:

searchCounter = 1

bookDict = {}

with open ('StratMasterKey.txt', 'rt') as myfile:

for line in myfile:
    question_pattern = re.compile((rf'(?<={searchCounter}\)).*'), re.IGNORECASE)
    result = question_pattern.search(line)
    if result != None: 

        bookDict[searchCounter] = result[0] 
        searchCounter +=1

相关问题 更多 >