# StringContainsQ, but anywhere in order

I am trying to find a string within a string, but "anywhere", so long as it is in the right order.

For example

StringContainsQ["aabbc","ac"]


returns

False

but I want True, since ac does in fact occur interleaved as position 1 and then position 5 in aabbc, as well as at position 2 and then position 5.

Anywhere, but in the right order. So

For example

NewStringContainsQFunction["aabbc","ba"]


should return.

False

Is there a nice way to do this, apart from searching letter by letter, until the string is built?

StringMatchQ["aabbc", "*a*c*"]


True

StringMatchQ["aabbc", "*b*a*"]


False

You can also use LongestCommonSequence to construct a function

ClearAll[strngCntnsQ]
strngCntnsQ = LongestCommonSequence[##] == #2 &;

strngCntnsQ["aabbc", "ac"]


True

strngCntnsQ["aabbc", "ba"]


False

• The second function is by far the best answer on here, since it immediately generalizes to longer second strings without needing to tweak it with *s etc. – Greg Martin Jan 29 '20 at 1:27
• @GregMartin That's true, but it's also far slower than a simple string pattern for non-trivial amounts of data. If you need efficiency, regular expressions or string patterns are much better. – Sjoerd Smit Jan 29 '20 at 9:14
• @GregMartin StringRiffle[Characters@"whatever", {"*", "*", ""}] – Kuba Jan 29 '20 at 9:30

Is this what you need?

StringContainsQ["aabbc","a" ~~ ___ ~~ "c"]


True

The following documentation pages should help you get going with string patterns in Wolfram Language:

edit Here is a function that generalizes this idea to strings of arbitrary length:

NewStringContainsQFunction[str1_String, str2_String] :=
StringContainsQ[
str1,
StringExpression @@ Riffle[Characters[str2], ___]
]

NewStringContainsQFunction["aabbc", "ac"]
NewStringContainsQFunction["aabbc", "ba"]


True

False

True

StringContainsQ["aaabc", RegularExpression["a.*c"]]


True