7
$\begingroup$

Maybe there is a knot in my head, but I would expect that

StringMatchQ["IP1", "IP"]

should return True (which it does not) just as

StringFreeQ["IP1", "IP"]

returns False (which it does). What am I missing?

$\endgroup$
  • 2
    $\begingroup$ If StringFreeQ is to strings as FreeQ is to expressions, then StringMatchQ is to strings as MatchQ, and not as MemberQ, is to expressions $\endgroup$ – Rojo Aug 27 '12 at 13:02
  • $\begingroup$ Related: (8945) $\endgroup$ – Mr.Wizard Mar 23 '15 at 12:22
15
$\begingroup$

StringMatchQ tests the pattern, and "IP1" doesn't match the pattern "IP", it does match the pattern ___~~"IP"~~___, but that's a different pattern! Similarly you could write your pattern as StringMatchQ["IP1", "IP*"]

StringFreeQ however doesn't just test the entire string, it tests every substring, so in effect the ___~~pattern~~___ is added by the function itself to your pattern.

$\endgroup$
  • 1
    $\begingroup$ StringMatchQ["IP1", "*IP*"] is the more appropriate equivalent to StringMatchQ["IP1", ___~~"IP"~~___], no? $\endgroup$ – J. M. is in limbo Aug 27 '12 at 13:18
  • $\begingroup$ Thanks, that helps a lot. I find it also odd that StringMatchQ["IP1", RegularExpression["IP"]] is False. $\endgroup$ – Karsten W. Aug 27 '12 at 13:37
  • $\begingroup$ @J.M. Yes, I was referring to his pattern in particular, however i suppose that wasn't clearly stated. $\endgroup$ – jVincent Aug 27 '12 at 13:55
  • 2
    $\begingroup$ @KarstenW. RegularExpression["IP"] is an exact "pattern", so you are asking if your string is equal to "IP", in other languages the pattern would be "^IP$". If you want to match anything containing IP, you have to specify the "anything containing" part of the pattern. StringMatchQ["IP1", RegularExpression[".*IP.*"]] is True. $\endgroup$ – jVincent Aug 27 '12 at 13:57
  • $\begingroup$ @Karsten, in short, StringMatchQ[] doesn't implicitly insert wildcards; if you want wildcards, you need to explicitly put them in. $\endgroup$ – J. M. is in limbo Aug 27 '12 at 13:59
3
$\begingroup$

If you like to think in negatives and avoid regular expressions:

!StringFreeQ["IP1", "IP"]

True

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.