如何匹配用特殊字母和/或括号括起来的字符?

时间:2019-07-10 16:37:26

标签: python regex

我试图用python编写正则表达式,但是很难同时捕获'<<'和'«'。 下面的正则表达式是我尝试过的,但没有捕获到我想要的。

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

我使用regex试图捕获3种类型的字符串。

  1. << {WORD} >>
  2. «{WORD}»
  3. {WORD}
    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}"]

1 个答案:

答案 0 :(得分:3)

如果我们的示例可能只限于所列示例,我们可以从以下表达式开始:

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

使用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))

this demo的右上角对表达式进行了说明,如果您想探索/简化/修改它,在this link中,您可以观察它如何与某些示例输入步骤匹配一步一步,如果您喜欢。