首页 > 解决方案 > 如何匹配被特殊字母和/或括号包围的字符?

问题描述

我试图在 python 中编写正则表达式语句,但很难同时捕获 '<<' 和 '«'。以下正则表达式是我尝试过的,但它没有按我的意愿捕获。

regex = "(<<)?«?{\w+}»?(>>)?(?=(\?|,|.|\s))"

regex试图捕捉 3 种类型的字符串。

  1. <<{字}>>
  2. “{单词}”
  3. {单词}
    sent1 = "Do you want to eat «{Food}»? %[Y](A:y) %[N](A:n)"
    sent2 = "You were drinking <<{coldBeverage}>>, do you want to drink <<{hotBeverage}>> instead?"
    sent3 = "I am a {animal} who can talk."

我希望我可以按以下方式运行正则表达式:

    re.findall(regex, sent1) = ["«{Food}»"]
    re.findall(regex, sent2) = ["<<{coldBeverage}>>", "<<{hotBeverage}>>"]
    re.findall(regex, sent3) = ["{animal}"]

标签: pythonregex

解决方案


如果我们的样本可能仅限于列出的那些,我们可以从这个表达式开始:

(«{[^»]+»|<<{[^>]+>>|{[^}]+})

测试re.finditer

import re

regex = r"(«{[^»]+»|<<{[^>]+>>|{[^}]+})"

test_str = ("    sent1 = \"Do you want to eat «{Food}»? %[Y](A:y) %[N](A:n)\"\n"
    "    sent2 = \"You were drinking <<{coldBeverage}>>, do you want to drink <<{hotBeverage}>> instead?\"\n"
    "    sent3 = \"I am a {animal} who can talk.\"\n\n"
    " re.findall(regex, sent1) = [\"«{Food}»\"]\n"
    "    re.findall(regex, sent2) = [\"<<{coldBeverage}>>\", \"<<{hotBeverage}>>\"]\n"
    "    re.findall(regex, sent3) = [\"{animal}\"]")

matches = re.finditer(regex, test_str)

for matchNum, match in enumerate(matches, start=1):

    print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))

    for groupNum in range(0, len(match.groups())):
        groupNum = groupNum + 1

        print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))

测试re.findall

import re

regex = r"(«{[^»]+»|<<{[^>]+>>|{[^}]+})"

test_str = ("    sent1 = \"Do you want to eat «{Food}»? %[Y](A:y) %[N](A:n)\"\n"
    "    sent2 = \"You were drinking <<{coldBeverage}>>, do you want to drink <<{hotBeverage}>> instead?\"\n"
    "    sent3 = \"I am a {animal} who can talk.\"\n\n"
    " re.findall(regex, sent1) = [\"«{Food}»\"]\n"
    "    re.findall(regex, sent2) = [\"<<{coldBeverage}>>\", \"<<{hotBeverage}>>\"]\n"
    "    re.findall(regex, sent3) = [\"{animal}\"]")

print(re.findall(regex, test_str))

该表达式在此演示的右上角面板中进行了说明,如果您希望探索/简化/修改它,并且在此链接中,您可以逐步观看它如何与一些示例输入匹配,如果您愿意的话。


推荐阅读