正则表达式–两种方式提取标签及其内容。
if(1){
QString targetString = "<tag1>Content1</tag1> <tag2>Content2</tag2> <tag3>Content3</tag3>";
QRegularExpression regex("<(.*?)>(.*?)</\\1>");
QRegularExpressionMatchIterator matchIterator = regex.globalMatch(targetString);
while (matchIterator.hasNext()) {
QRegularExpressionMatch match = matchIterator.next();
QString tag = match.captured(1);
QString content = match.captured(2);
qDebug() << "Tag:" << tag;
qDebug() << "Content:" << content;
}
}
if(1){
QString input_str = "<div>This is some text.</div><span>More content.</span>";
QString replacement_str = "New content";
int pos = 0;
QRegularExpression regex("<(div|span)>(.*?)</\\1>");
QRegularExpressionMatch match = regex.match(input_str, pos);
QStringList replacedStrings;
while (match.hasMatch()) {
QString tag = match.captured(1);
QString matchedString = match.captured(2);
qDebug()<<"tag "<<tag<<"matchedString "<<matchedString;
replacedStrings << replacedString;
pos = match.capturedEnd();
match = regex.match(input_str, pos);
}
qDebug()<<"replacedStrings "<<replacedStrings;
}
```