How to split QString using QRegex?
-
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: Regex Online Tester
I have tried with \(.*?\)
But in code, it's not working.I have tried with many expressions but not working
What I'm missing?
-
@npatil15 said in How to split QString using QRegex?:
But in code, it's not working.
First please use QRegularExpression, second please show us the code. Be aware that you have to escape '\'.
-
I have tried the below method.
For reference, I have used 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.
-
@KroMignon said in How to split QString using QRegex?:
@npatil15 Hmm, I think you should do it like this:
QStringList list = query.split(QRegularExpression("({\\(|\\)-\\(|\\)})"), QString::SkipEmptyParts);
Thanks a lot, it works like charm. :)
-
Hi,
Out of curiosity, are you needing to split ? Otherwise, you could also use QRegularExpession::match and extract each side from the returned QRegularExpressionMatch object. It might look a bit more complicated but you will also be more precise in what you are extracting.
-
@SGaist ,
Yes I'm about to drop reply.
The solution mentioned by @KroMignon , it works if I have specific expressions, but I may have multiple expressions like: {($..Properties[*])-($..Layer_Index)+($..Name==Value())/($..Properties(Name==True))}
So here in the above expression, I want to split text like:
- $..Properties[*]
- $..Layer_Index
- $..Name==Value()
- $..Properties(Name==True)
And more over want to split the math symbol like, -,+,/. To do the mathematical operations.
I have tried with your suggestions as mentioned in below code:
QString query("{($..Properties[*])-($..Layer_Index)+($..Name==Value())/($..Properties(Name==True))}"); QRegularExpression re; re.setPattern("\\(.*?\\)"); QRegularExpressionMatch match = re.match(query); qDebug()<<"Match 0: "<<match.captured(0); qDebug()<<"Match 1: "<<match.captured(1); qDebug()<<"Match 2: "<<match.captured(2);
Output: Match 0: "($..Properties[*])" Match 1: "" Match 2: ""
I think I'm passing incorrect pattern, which I didnt understanding, how to split all between the ( ) brackets but not the brackets inside bracket like Name==True from ($..Properties(Name==True)).
What I'm missing here to get a list of all split strings? -
Do you have some sort of DSL ?