【发布时间】:2019-05-08 11:43:52
【问题描述】:
我正在尝试使用 QRegularExpression 获取不同捕获组中 xml 标记的所有属性。我使用匹配标签的正则表达式,我设法获取包含属性值的捕获组,但使用量词,我只得到最后一个。
我使用这个正则表达式:
<[a-z]+(?: [a-z]+=("[^"]*"))*>
我想用这个文本得到“a”和“b”:
<p a="a" b="b">
代码如下:
const QString text { "<p a=\"a\" b=\"b\">" };
const QRegularExpression pattern { "<[a-z]+(?: [a-z]+=(\"[^\"]*\"))*>" };
QRegularExpressionMatchIterator it = pattern.globalMatch(text);
while (it.hasNext())
{
const QRegularExpressionMatch match = it.next();
qDebug() << "Match with" << match.lastCapturedIndex() + 1 << "captured groups";
for (int i { 0 }; i <= match.lastCapturedIndex(); ++i)
qDebug() << match.captured(i);
}
还有输出:
Match with 2 captured groups
"<p a=\"a\" b=\"b\">"
"\"b\""
是否可以使用量词 * 获取多个捕获组,或者让我使用 QRegularExpressionMatchIterator 和字符串文字上的特定正则表达式进行迭代?
【问题讨论】:
-
为什么是正则表达式?见a non-regex approach here。 SO thread 在这里。更通用的:How to parse an HTML file with QT?
-
这是因为我在 QSyntaxHighlighter 中使用了这个 ^^
标签: c++ regex qt regex-group qregularexpression