5
$\begingroup$

I have a list myList that contains several strings. I wish to use Position to find the positions of strings in myList that match the pattern "A" ~~ ___.

The first overload for Position in the documentation is:

Position[expr, pattern] gives a list of the positions at which objects matching pattern appear in expr.

Is there a difference between a (general) pattern and a string pattern? In the following code, why does the first call to Position yield an empty list ({}), while the second call to Position gives the positions of the strings in myList that match "A" ~~ ___?

myList = {"AB", "B", "AABB", "BAA", "ABB"};
Position[myList, "A" ~~ ___, {1}, Heads -> False]
Position[myList, _?(StringMatchQ[#, "A" ~~ ___] &), {1}, Heads -> False]

{}

{{1}, {3}, {5}}

Is "A" ~~ ___ not a pattern?

$\endgroup$

2 Answers 2

4
$\begingroup$

Yes, there is a difference. "A" ~~ ___ is not a pattern but a StringExpression, which you can see by observing its FullForm:

"A" ~~ ___ // FullForm
StringExpression["A", BlankNullSequence[]]

StringExpression is used as an analog of Pattern for strings (more about Working with String Patterns).

Therefore, there are two different functions: MatchQ (with corresponding Position) and StringMatchQ (with corresponding StringPosition). While MatchQ expects a pattern, StringMatchQ expects a StringExpression (or RegularExpression), which is mentioned under the first bullet point in Details and Options.

$\endgroup$
1
$\begingroup$

As Domen already pointed out, Pattern and StringExpression differ. Therefore, what you can do, is to use a pattern together with a PatternTest that request a boolean function. As boolean function you choose:

StringMatchQ[#, "A" ~~ ___] &

With this the pattern looks like:

_?(StringMatchQ[#, "A" ~~ ___] &)

Now you approach works:

myList = {"AB", "B", "AABB", "BAA", "ABB"};
Position[myList, _?(StringMatchQ[#, "A" ~~ ___] &), {1},Heads -> False]

{{1}, {3}, {5}}
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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