我有这个正则表达式模式:(?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
此正则表达式还使用回溯来检查是否使用字符串中的对
(
和)
进行转义。例如,不应检测到这两个样本,因为在(
和)
之前有一个:
hello my (friend|enemy) nice to see you again
hello my (friend|enemy) nice to see you again
当我使用在线网站检查它时,这种模式效果很好,但是当我尝试在python中运行时(我使用的是python 3.7(,它会抛出以下错误:re.error: missing ), unterminated subpattern at position 35
问题出在哪里?
编辑: 以下是我在 python 中使用它的方式:
pattern = "(?P<prefix>.*)(?<!\)((?P<words>.+)(?<!\))(?P<postfix>.*)"
match = re.search(pattern, line)
@Md Narimani 正如@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)
这是因为转义字符的问题。