How to pass regular expresion to QString.contains (reg expression) ??
-
I am testing /learning how to use regular expression.
I like this code to match all ASCII characters as words .When used like this ,
QRegularExpression re("[ -~]+");
it correctly matches first words in the inStringHowever when used in .contains it fails.
I have included two attempts to implement .contains with similar parameter passed.I am asking for help to write passed regular expression correctly.
My syntax pass by compiler but does not work.Please - no references to AI reg expression generators - they do not work when tested expression code is passed to Qt.
THANKS
if(inString.contains(^[ -~]+$ )) { text = "Match "; }else { text = " No match "; } qDebug() << text; textDEBUG->append(text); OR if(inString.contains("[ -~]+")) { text = "Match "; }else { text = " No match "; } qDebug() << text; textDEBUG->append(text);
-
@AnneRanch
if(inString.contains(^[ -~]+$ ))
This will not compile as you are not passing it either a
QString
or aQRegularExpression
. You will get a syntax error.if(inString.contains("[ -~]+"))
This will compile. But because you don't pass any regular expression, only a plain string, it will look to see whether that literal string appears in your test string, which it won't.
You meant:
if(inString.contains(QRegularExpression("[ -~]+")))
which will tell you whether your string contains one or more ASCII characters.
That would be true if your string contains a mixture of ASCII and non-ASCII characters. If you want to "fail" on any non-ASCII characters (i.e. only succeed on all ASCII characters) you want something like:
if (QRegularExpression("^[ -~]+$").match(inString).hasMatch())