【问题标题】:Match nested capture groups with quantifiers using QRegularExpression使用 QRegularExpression 将嵌套的捕获组与量词匹配
【发布时间】: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 和字符串文字上的特定正则表达式进行迭代?

【问题讨论】:

标签: c++ regex qt regex-group qregularexpression


【解决方案1】:

This expression 可能会帮助您简单地捕获这些属性,并且它没有左右界限:

([A-z]+)(=\x22)([A-z]+)(\x22)

图表

此图显示了表达式的工作原理,如果您想知道,您可以在此 link 中可视化其他表达式:


如果你想为它添加额外的边界,你可能想要这样做,你可以进一步扩展它,也许是similar to

(?:^<p )?([A-z]+)(=\x22)([A-z]+)(\x22)

正则表达式测试

const regex = /(?:^<p )?([A-z]+)(=\x22)([A-z]+)(\x22)/gm;
const str = `<p attributeA="foo" attributeB="bar" attributeC="baz" attributeD="qux"></p>`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }
    
    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}

【讨论】:

  • 感谢您的帮助。但是在这里我仍然必须使用正则表达式引擎(QRegularExpressionMatchIterator)进行循环,并且我们不能在一个匹配的不同捕获组中拥有所有属性。对吗?
猜你喜欢
  • 1970-01-01
  • 2014-07-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-12
  • 1970-01-01
相关资源
最近更新 更多