我正在尝试在模板中匹配%foo%形式的字符串。上下文:目标是将%foo%替换为存储过程返回中的列foo的值。
我不能让它发挥作用。一个开始我认为我的模板的UTF8编码是我的麻烦的根源。但即使是下面也会失败:
#include <QCoreApplication>
#include <QRegExp>
#include <iostream>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QString str = "__%foo%____";
std::cout << "with regex: %(.*)%" << std::endl;
QRegExp re("%(.*)%",Qt::CaseInsensitive);
re.indexIn(str);
for(int pos = 0; pos < re.captureCount(); ++pos)
{
std::cout << re.cap(pos).toStdString() << std::endl;
}
std::cout << "with regex: \\%(.*)\\%" << std::endl;
QRegExp re2("\\%(.*)\\%",Qt::CaseInsensitive);
re2.indexIn(str);
for(int pos = 0; pos < re2.captureCount(); ++pos)
{
std::cout << re2.cap(pos).toStdString() << std::endl;
}
std::cout << "with regex: %([^%])%" << std::endl;
QRegExp re3("%([^%])%",Qt::CaseInsensitive);
re3.indexIn(str);
for(int pos = 0; pos < re3.captureCount(); ++pos)
{
std::cout << re3.cap(pos).toStdString() << std::endl;
}
std::cout << "with regex: \\%([^\\%])\\%" << std::endl;
QRegExp re4("\\%([^\\%])\\%",Qt::CaseInsensitive);
re4.indexIn(str);
for(int pos = 0; pos < re4.captureCount(); ++pos)
{
std::cout << re4.cap(pos).toStdString() << std::endl;
}
std::cout << "with regex: \\x25([^\\x25])\\x25" << std::endl;
QRegExp re5("\\x25([^\\x25])\\x25",Qt::CaseInsensitive);
re5.indexIn(str);
for(int pos = 0; pos < re5.captureCount(); ++pos)
{
std::cout << re5.cap(pos).toStdString() << std::endl;
}
std::cout << "with regex: \\%(.*)\\%" << std::endl;
QRegExp re6("\\%(.*)\\%",Qt::CaseInsensitive);
re6.indexIn(str);
for(int pos = 0; pos < re6.captureCount(); ++pos)
{
std::cout << re6.cap(pos).toStdString() << std::endl;
}
return a.exec();
}
输出:
with regex: %(.*)%
%foo%
with regex: \%(.*)\%
%foo%
with regex: %([^%])%
with regex: \%([^\%])\%
with regex: \x25([^\x25])\x25
with regex: \%(.*)\%
%foo%
我只想捕获foo,而不是'%'
答案 0 :(得分:1)
确定每一个
int pos = 0; pos < re.captureCount(); ++pos
作为
int pos = 0; pos <= re.captureCount(); ++pos
我有输出:
with regex: %(.*)%
%foo%
foo
with regex: \%(.*)\%
%foo%
foo
with regex: %([^%])%
with regex: \%([^\%])\%
with regex: \x25([^\x25])\x25
with regex: \%(.*)\%
%foo%
foo
cap(0)显然匹配整个表达式
答案 1 :(得分:0)
使用非捕获组:
QString txt="____%foo%___some%__";
QRegExp rx("(?:%)[^%]*(?:%)");
pos = rx.indexIn(txt, 0);
rx.capturedTexts().at(1); //holds foo
如果您需要所有匹配项,请使用indexIn循环并提供pos + rx.matchedLenght()而不是0