【发布时间】:2019-01-28 09:13:38
【问题描述】:
我是answering this question。考虑这个字符串
str1 = '{"show permission allowed to 16": "show permission to 16\\nSchool permissions from group 17:student to group 16:teacher:\\n\\tAllow ALL-00\\nSchool permissions from group 18:library to group 16(Temp):teacher:\\n\\tNo Allow ALL-00\\nSchool permissions from group 20:Gym to group 16:teacher:\\n\\tCheck ALL-00\\nRTYAHY: FALSE\\nRTYAHY: FALSE\\n\\n#"}'
并假设我想提取每个子字符串 from group 之后的数字和 \\t 之后的子字符串具有最小匹配字符串。
我用下面的正则表达式做到了这一点
import re
res = re.findall(r'from group (\d+).*?\\t(.*? ALL-..)', str1)
输出是:
[('17', 'Allow ALL-00'), ('18', 'No Allow ALL-00'), ('20', 'Check ALL-00')]
现在在我提取的每个子字符串之间(数字和\t 之后的子字符串)可能有一个可选的子字符串,其值为Temp 我想提取(如果存在)。例如在18 和No Allow ALL-00 之间有一个子字符串Temp 我想提取。
我尝试如下使用?:
res = re.findall(r'from group (\d+).*?(Temp)?.*?\\t(.*? ALL-..)', str1)
但结果元组的相应第二个元素始终为空:
[('17', '', 'Allow ALL-00'), ('18', '', 'No Allow ALL-00'), ('20', '', 'Check ALL-00')]
当我期待这样的事情时:
[('17', '', 'Allow ALL-00'), ('18', 'Temp', 'No Allow ALL-00'), ('20', '', 'Check ALL-00')]
在这种情况下如何提取子字符串?我做错了什么?
还有一个问题:假设我希望我的结果列表没有这个元素(包含Temp 的那个):我应该只使用[^],然后使用相应的匹配模式吗?
【问题讨论】:
标签: python regex python-3.x substring