我正在用 python 编写一个正则表达式来捕获 SSI 标签内的内容。
我想解析标签:
<!--#include file="/var/www/localhost/index.html" set="one" -->
分为以下组件:
include
、 echo
或 set
) =
符号 "
的 问题是我不知道如何获取这些重复组,因为名称/值对可能会在标签中出现一次或多次 。我花了几个小时在这上面。
这是我当前的正则表达式字符串:
^\<\!\-\-\#([a-z]+?)\s([a-z]*\=\".*\")+? \-\-\>$
它捕获第一组中的
include
和第二组中的 file="/var/www/localhost/index.html" set="one"
,但我所追求的是:group 1: "include"
group 2: "file"
group 3: "/var/www/localhost/index.html"
group 4 (optional): "set"
group 5 (optional): "one"
(continue for every other name="value" pair)
I am using this site to develop my regex
最佳答案
抓取所有可以重复的内容,然后单独解析它们。这也可能是命名组的一个很好的用例!
import re
data = """<!--#include file="/var/www/localhost/index.html" set="one" reset="two" -->"""
pat = r'''^<!--#([a-z]+) ([a-z]+)="(.*?)" ((?:[a-z]+?=".+")+?) -->'''
result = re.match(pat, data)
result.groups()
('include', 'file', '/var/www/localhost/index.html', 'set="one" reset="two"')
然后遍历它:
g1, g2, g3, g4 = result.groups()
for keyvalue in g4.split(): # split on whitespace
key, value = keyvalue.split('=')
# do something with them
关于python - 使用 RegEx 在 Python 中捕获重复组(参见示例),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24540347/