python - 如何匹配被特殊字母和/或括号包围的字符?
问题描述
我试图在 python 中编写正则表达式语句,但很难同时捕获 '<<' 和 '«'。以下正则表达式是我尝试过的,但它没有按我的意愿捕获。
regex = "(<<)?«?{\w+}»?(>>)?(?=(\?|,|.|\s))"
我regex
试图捕捉 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}"]
解决方案
如果我们的样本可能仅限于列出的那些,我们可以从这个表达式开始:
(«{[^»]+»|<<{[^>]+>>|{[^}]+})
测试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))
该表达式在此演示的右上角面板中进行了说明,如果您希望探索/简化/修改它,并且在此链接中,您可以逐步观看它如何与一些示例输入匹配,如果您愿意的话。
推荐阅读
- javascript - 如何从一个包含对象的大数组中获取两个单独的数组?
- oracle-apex - Oracle Apex 主页 URL 问题 - 固定页面不是动态的
- javascript - 获取两个字符JQuery之间的文本
- php - 出于安全原因,shell_exec() 已被禁用
- javascript - 如何在 IIS 服务器上托管的 Angular 应用程序中获取客户端的 Windows 登录信息?
- python - 使用 Python 识别局域网上连接的设备路由器
- matlab - 如何获得符号系统的数值?
- google-app-engine - Google Cloud Build - source-context.json SHA 不匹配
- c# - 没有脚本的 Unity gameObject 正在达到碰撞方法
- c++ - 标准::向量
::emplace_back 在右值引用上