[SOLVED] I could not change in a special part of string by using Qregexp
-
Hello,
i am trying to change a specific part of string. my string like this.
"size 2 - (48-50 size)"and i want to change it like
"size 2 - (48&50 size)"because im using - char for split size and color in my string list.
i cant use change the last - to & because this is a special condition.i use that code:
QString fullVariants = "size 2 - (48-50 size)"
fullVariants.replace(QRegExp("[0-9]{1,2}\-[0-9]{1,2}"), "\1&\2");
qDebug() << fullVariants;but debug says, "size 2 (& size)"
can you help me? i didnt undertand why /1 and /2 doesnt work for changing a part of string.
Thanks. -
You need to escape the backslashes in the after argument:
fullVariants.replace(QRegExp("[0-9]{1,2}\-[0-9]{1,2}"), "\\1&\\2");
-
@wlof it gives like that 'size 2 (\1&\2 size)' it does not work..
-
Ah, that's because you're missing the capturing parentheses in the regexp. Try this:
fullVariants.replace(QRegExp("([0-9]{1,2})\-([0-9]{1,2})"), "\\1&\\2");
-
Hi and welcome to devnet,
you have also to capture the components
fullVariants.replace(QRegExp("([0-9]{1,2})-([0-9]{1,2})"), "\\1&\\2");
-
@wlof it works, thank you very much.
-
You're welcome! :)
Remember to mark the topic as solved!
-
@kybernetes Keep in mind that
\-
is not recognized -
Hi and welcome to devnet,
To help you build regular expression with QRegExp there's the RegExp Tool from Qt's example.
If you're using Qt 5 you should also consider using QRegularExpression which is more powerful and should be faster.