如何匹配由特殊字母和/或括号包围的字符?

2024-10-05 14:29:53 发布

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

我试图用python编写regex语句,但很难同时捕获“<;<;”和“«”。 下面的正则表达式是我尝试过的,但是它没有捕获到我想要的内容。你知道吗

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

使用regex我尝试捕获3种类型的字符串。你知道吗

  1. <;{WORD}>;<;{WORD}>
  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."

我希望我可以按以下方式运行regex:

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

Tags: toltgtreyoufood单词regex
1条回答
网友
1楼 · 发布于 2024-10-05 14:29:53

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

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

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中,如果您愿意,您可以一步一步地观察它如何与一些示例输入匹配。你知道吗

相关问题 更多 >