Reputation: 2503
I've worked on regular expression on Qt , I want to replace all sub string with specific regular expression with image.
my tag struct is combination of <
, sml
, digits (one or two)
and />
and my QString is draftMsg
. It will work if I use regular expression once.
for example : "hello <sml7/>
" will be change to hello and photo with label 7 in my directory.
Here is my code:
QRegExp rxlen("<sml(\\d{1,2})/>");
if (draftMsg.contains(rxlen))
{
QString str = rxlen.capturedTexts()[1];
int index = str.toInt();
smileyClicked(index-1);
m_messageEdit->insertHtml(QString("<img src=\":images/smiley/%1_64.png\" width=%2 />")
.arg(index, 2, 10, QLatin1Char('0')).arg(smileyWidth));
draftMsg = draftMsg.remove(rxlen);
}
Actually it replace wrongly when I write string like : "hello <sml7/><sml1/>
". It will replace both tag to image with label 7.
I searched and I found it. I trying to use captureCount() to keep Regular expression's number and use it.
I've created this function:
void MessageDialog::regInMessage(QString pattern, QString string)
{
QRegExp regex(pattern);
if (regex.indexIn(string) < 0) {
qDebug("Can't find a match.");
return;
}
qDebug() << regex.captureCount();
}
But it gives me "1" instead of two.
Any suggestion to count regular expression on my QString?
Upvotes: 4
Views: 18894
Reputation: 4286
Capture - is a string, that matches an expression within brackets. In your regex <sml(\\d{1,2})/>
there is only one bracket pair, so the captureCount
returns 1. In order to process all entrances of regex in a string you need to do something like this (example from Qt's help):
QRegExp rx("(\\d+)");
QString str = "Offsets: 12 14 99 231 7";
QStringList list;
int pos = 0;
while ((pos = rx.indexIn(str, pos)) != -1) {
list << rx.cap(1);
pos += rx.matchedLength();
}
// list: ["12", "14", "99", "231", "7"]
Also, if you want to replace a string, a good idea would be to use QString & QString::replace ( const QRegExp & rx, const QString & after ).
UPDATE
I'm using QString::replace like this: – afn
QString draftMsg = query.value(0).toString(); QRegExp rx(""); int pos = 0; QStringList list; while ((pos = rx.indexIn(draftMsg, pos)) != -1) { list << rx.cap(1); pos += rx.matchedLength(); } for (int k=0 ; k < list.length() ; ++k) draftMsg.replace(QRegExp(""), ""); – afn
but it doesn't work – afn
Used your code.
In: "hello <sml7/><sml1/>"
Out: "hello <img src=":images/smiley/7.png" width=%2 /><img src=":images/smiley/1.png" width=%2 />"
What were you expecting to get?
Also, all this code can be changed to this:
QString draftMsg = query.value(0).toString();
draftMsg.replace(QRegExp("<sml(\\d{1,2})/>")
, "<img src=\":images/smiley/\\1.png\" width=%2 />");
Upvotes: 3