Question

I would like to capture second occurence of the text replaced by a star in the following string:

&nbsp;SW * <br>

ie string starting with &nbsp;SW ending with <br> in a QString, using the RegEx with Qt.

an example here: the string is

&nbsp;&nbsp;SW = min(1, max(0, pow(10, -0.2 - 6.5 ) ** (1.0 / 0.2)))<br>

and expected result is

= min(1, max(0, pow(10, -0.2 - 6.5 ) ** (1.0 / 0.2)))

So far, i have QRegExp rx("^[\&nbsp;SW](.*)[<br>]$"); which is not compiling.

How would you do ?

Was it helpful?

Solution

The compilation issue is probably due to trying to escape the ampersand (\&). But other than that, your regex is mostly right, just overusing character groups ([]), they are not for grouping. This expression works in my tests: &nbsp;SW(.*)<br>, so in your case you'd do something like

QRegExp rx("&nbsp;SW(.*)<br>")

OTHER TIPS

the exact pattern was QLatin1String(".*&nbsp;SW([^<]*)<br>.*") and for capture this code was working for me

       QRegExp rx(QLatin1String(".*&nbsp;SW([^<]*)<br>.*"));

       int p = 0;
       QString cap ;
       if((p = rx.indexIn(str, p)) != -1) 
           cap = rx.cap(1).trimmed();

nota bene: should capture first occurrence for element within the parenthesis with cap(1) and not cap(0) which capture of the whole pattern and not the content of the parenthesis.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top