Does QRegularExpression class support conditional matching?
-
I am trying to match numbers in a text file using regular expression. I have tried the following expression:
match_number = QRegularExpression("\b[-+]?\d*[.]?\d+([eE][-+]?\d+)?\b");This matches pure numbers in the content. However, it also matches numbers appearing in comment lines. For example:
' This is comment 1
The "1" was also matched when I use the above expression. So I come up an idea that I can first determine whether the line starts with a ', if it does not, then I do match with the match_number expression. I have tried:QRegularExpression("(?(^(?!'))(\b[-+]?\d*[.]?\d+([eE][-+]?\d+)?\b))").
This gave an error:
"QRegularExpressionPrivate::doMatch(): called on an invalid QRegularExpression object"I have tried the expression using the Regular Expression tool of QCreator, the expression appeared red color that means it has an error. Seems that QRegularExpression does not support conditional matching, but I could not find any official document about what the features QRegularExpression class supports. Any one has any idea? Thanks in advance.
-
Hi Richard,
@Richard-Lee said in Does QRegularExpression class support conditional matching?:
QRegularExpression("(?(^(?!'))(\b[-+]?\d*[.]?\d+([eE][-+]?\d+)?\b))").
This gave an error:
"QRegularExpressionPrivate::doMatch(): called on an invalid QRegularExpression object"Well, if I paste your regular expression in [1], it says the same. So either pcre [2], the engine QRegularExpression uses, does not support it; or your expression really has an error.
Please note that, even if your regex is working fine in the online test tools, you still may need to edit it when using in C++ source code, e.g. replacing "\d" with "\\d" because the backslash has a special meaning for the compiler.
Edit: did you mean: "(?:(^(?!'))(\b[-+]?\d*[.]?\d+([eE][-+]?\d+)?\b))" (colon after first questionmark)?
-
Hi,
To add to @aha_1980, there's the QRegularExpression example that provides a tool to test your regular expressions with Qt and get the correctly formatted version.
-
@aha_1980 Thanks for replying. I made a mistake. I actually used "\\d" instead of "\d" in my code. So I believe my regular expression is correct in syntax.
I do not know much about the regular expression. What does the ?: differ from the ? when used for conditional matching?