PDA

View Full Version : How to split string using QRegex?



npatil15
13th April 2020, 13:39
Hello,

I want to split this: {($..Properties )-($..Layer_Index)}
Like: ("$..Properties ", "$..Layer_Index")

I have tried some examples and online regex tester, I'm getting output but it's not working here.

On this link: https://www.regextester.com/97589
I have tried with \(.*?\)
But in code, it's not working.

I have tried with many expressions but not working

What I'm missing?

d_stranz
13th April 2020, 16:34
What I'm missing?

Are you properly "escaping" your regex when you pass it as a QString?



"\\(.*?\\)"


If the strings you want to split are all this simple, why not just split on "-" and then remove the "(" and ")" using QString::left() and QString::right()?

npatil15
14th April 2020, 07:17
@d_stranz, I cant use the method you suggest because the sign between the two expressions can be changed to anything.

FOr reference I have use below code


QString query("{($..Properties )-($..Layer_Index)}");
QStringList list = query.split(QRegularExpression("\\(.*?\\)"));
qDebug()<<"Output: "<<list;

//Output --> Output: ("{", "-", "}")


And I have checked on many online regex testers like this one https://regexr.com/
And output is like bold marked: {($..Properties )-($..Layer_Index)}

So why there is so differences in this outputs.

ChrisW67
14th April 2020, 08:46
The first argument to QString::split() is the delimiter you want to split the string on. You are telling QString to split using parentheses-enclosed strings as the delimiter, and keep the other bits. You get the opening '{', the separating '-', and the closing '}' because these are the only bits outside the delimiters. Try this RE as the delimiter "[{}-]" with QString::SkipEmptyParts.

If you want to use a regular expression to match the bits of the strings you want then then that is better achieved with QRegularExpression.

npatil15
14th April 2020, 09:31
Thanks,

I have tried with other way, but it has small issue, look the code below,


QString query("{($..Properties )-($..Layer_Index)}");
QRegularExpression re;
re.setPattern("\\(.*?\\)");
QRegularExpressionMatch match = re.match(query);
qDebug()<<"Match 0: "<<match.captured(0);
qDebug()<<"Match 1: "<<match.captured(1);

//Output: Match 0: "($..Properties )"
// Match 1: ""


Here I didnt get the Match 1 as ($..Layer_Index), why ?

d_stranz
14th April 2020, 16:51
For one thing, QRegularExpressionMatch::captured() with a '0' argument returns the -entire- capture, not the first one. captured( 1 ) should be returning your first string, not the second. QRegularExpressionMatch::capturedTexts() will return all of them as a QStringList.

And try using QRegularExpression::globalMatch() instead of match().