Python regex错误:丢失),位置35处的子模式未终止

2024-04-26 10:47:45 发布

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

我有这个正则表达式模式:
(?P<prefix>.*)(?<!\\)\((?P<words>.+)(?<!\\)\)(?P<postfix>.*)

这个正则表达式应该匹配如下字符串:
hello my (friend|enemy) nice to see you again

prefix组应该捕获hello my
words组应捕获friend|enemy
postfix组应该捕获nice to see you again

这个正则表达式还使用lookbehinds检查是否在字符串中使用\()进行转义。例如,由于在()之前有一个\,所以这两个样本不应该被检测到:
hello my \(friend|enemy) nice to see you again
hello my (friend|enemy\) nice to see you again

当我使用在线网站检查它时,这个模式运行得很好,但是当我尝试用python运行时(我使用的是python3.7),它会抛出以下错误:
re.error: missing ), unterminated subpattern at position 35

有什么问题?你知道吗

编辑: 下面是我在python中如何使用它:

pattern = "(?P<prefix>.*)(?<!\\)\((?P<words>.+)(?<!\\)\)(?P<postfix>.*)"
match = re.search(pattern, line)

Tags: to字符串refriendyouhelloprefixmy
1条回答
网友
1楼 · 发布于 2024-04-26 10:47:45

@Md纳里马尼 正如@erhumoro在评论中建议的,而不是:

line = "hello my (friend|enemy) nice to see you again"
pattern = "(?P<prefix>.*)(?<!\\)\((?P<words>.+)(?<!\\)\)(?P<postfix>.*)"
match = re.search(pattern, line)

执行:

line = "hello my (friend|enemy) nice to see you again"
pattern = r"(?P<prefix>.*)(?<!\\)\((?P<words>.+)(?<!\\)\)(?P<postfix>.*)"
match = re.search(pattern, line)

这是因为转义字符的问题。你知道吗

相关问题 更多 >