QRegularExpression to replace match
-
Given the
str
:border: 2px solid #a4002c; /**/
I'm trying to replace just the value between
#
and;
in this casea4002c
I've tested the regex I'm using here and seen to be working:
https://regex101.com/r/PS1ZXU/1But when i use it on qt:
auto re = QRegularExpression (R"(border.*?#\s*(.*);\s*\/)"); str = str.replace(re, "12ff00"));
The
str
mentioned above is being replaced to:12ff00**/
I'm probably missing something in the
.replace
line
specially here:(re, "12ff00"));
I'm not good with regex, appreciate any help on this task.
-
Given the
str
:border: 2px solid #a4002c; /**/
I'm trying to replace just the value between
#
and;
in this casea4002c
I've tested the regex I'm using here and seen to be working:
https://regex101.com/r/PS1ZXU/1But when i use it on qt:
auto re = QRegularExpression (R"(border.*?#\s*(.*);\s*\/)"); str = str.replace(re, "12ff00"));
The
str
mentioned above is being replaced to:12ff00**/
I'm probably missing something in the
.replace
line
specially here:(re, "12ff00"));
I'm not good with regex, appreciate any help on this task.
@Roberrt
Your regular expression in itself is fine at matching all the way to the first/
, as regex101 shows you. Your problem is in the replacement: you replace all of that match with your12ff00
, hence the final result of12ff00**/
. You would want to preserve much more of the original string.There are many ways of doing this, depending on exactly what you want. Reading your original requirement:
I'm trying to replace just the value between
#
and;
in this casea4002c
let's do just that?
auto re = QRegularExpression("#[^;]*"); str = str.replace(re, "#12ff00"));
"Replace a
#
followed by any number of non-;
characters by#12ff00
. The rest of the string (before and after the match) remains as-is.As I say, there are many other possibilities depending on exactly what your requirement is. Maybe you will say "but I must only do this if there is
border
there" or "fine, but I'd like to make my original regular expression work".P.S.
I don't think you noticed that at regex101 in the left-hand pane under FUNCTION you had the default of Match. You can test by changing that to Substitution. I have done so for your original expression at https://regex101.com/r/ZgjhKI/1 , so you can see.