Solved Exact match in QStringList
-
i have a qstringlist, say
QStringList list; list << "abcd" << "efgh";
and i wanna match an exact string, i.e.
if(!list.contains(text)) { // do something }
the thing is, i wanna catch an exact match, for example "acbd", but when i pass "cd" as an argument to contains(), it returns true, since "cd" is contained in "abcd".
and contains won't match with regexp.
what can i do?
-
Hi,
Then use filter or indexOf with a QRegularExpression.
-
but they search for a substring, i need exact match of a string
-
@user4592357
Hi
A low tech solution could just beQStringList list; list << "anders" << "peter" << "hanspeter" << "polka" << "hans"; foreach (const QString& var, list) { if ( var == "hans" ) qDebug() << "HIT!"; }
But that dont allow for Case sensitive matching.
-
that's what i currently have. i don't care aboit case sensitivity in my problem. but i wanted a more "sophisticated" method, or to be precise, a shorter and already implemented one
-
There's not even a need for QRegularExpression.
qDebug() << list.indexOf("cd") << list.indexOf("abcd");
You'll get
-1
and0
.So you replace your current
if
condition withlist.indexOf(text) == -1
and you're good to go. -
@SGaist
I don't get what you're proposing. Are you sayingQStringList::indexOf
only finds complete-element matches, not substrings (the docs don't make this clear to me), but the OP usedQStringList::contains()
and that does not behave same? Plus, docs say that all overloads ofQStringList::indexOf
take a regular expression type argument, how doeslist.indexOf("cd")
return-1
? -
indexOf documentation states: "the first exact match" well except the overload for QRegularExpression but that might be a documentation issue.
-
It's indeed a documentation issue. It works as the other overload.
-
that is why i was confused by looking at the docs. sorry, anyways.
indexOf() does what i was looking for -
@SGaist
SoindexOf
, which only accepts a regular expression, does a^pattern$
("exact" match?) against each element, andcontains
does a sub string (across all elements concatenated or each element individually?) ? -
@JNBarchan
that's what my experience was
-
Just one thing: you have something strange going on. Contains does an exact string comparison (depending on the case sensitivity chosen) so you should verify that you really did pass only two characters.
QStringList list; list << "abcd" << "efgh" << "bcfg"; qDebug() << list.indexOf(QRegularExpression("bc")) << list.indexOf(QRegularExpression("abcd")); qDebug() << list.contains("bc") << list.contains("abcd");
Returns:
-1 0 false true
so in fact working as expected.