Qt - how to define regex in QString
I was working in regex in Qt, I want to replace all sub-string with a specific regex with an image.
my tag struct - a combination of <
, sml
, digits (one or two)
and />
, and my a QString draftMsg
. It will work if I use the regex once.
for example: "hello <sml7/>
" will be changed to a greeting and a photo labeled 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);
}
In fact, it incorrectly replaces when I write a line like: "hello <sml7/><sml1/>
". It will replace both tags to the image with the 7 tag.
I searched and found it . I am trying to use captureCount () to store the regex number and use it.
I 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 he gives me "1" instead of two.
Any suggestion to count the regex on my QString?
source to share
Capture is a string that matches the parenthesized expression. Your regex <sml(\\d{1,2})/>
only has one pair of parentheses, so it captureCount
returns 1. To process all regex inputs in a string, you need to do something like this (example from the Qt 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, it would be a good idea to use QString and QString :: replace (const QRegExp and rx, const QString and after) .
UPDATE
I am using QString :: replace like this: - afn
QString draftMsg = query.value (0) .toString (); QRegExp rd ("); int pos = 0; QStringList list; whereas ((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
Your code is used.
IN: "hello <sml7/><sml1/>"
Output: "hello <img src=":images/smiley/7.png" width=%2 /><img src=":images/smiley/1.png" width=%2 />"
What did you expect to receive?
In addition, all this code can be changed as follows:
QString draftMsg = query.value(0).toString();
draftMsg.replace(QRegExp("<sml(\\d{1,2})/>")
, "<img src=\":images/smiley/\\1.png\" width=%2 />");
source to share