Message Boards Message Boards

0
|
5623 Views
|
3 Replies
|
4 Total Likes
View groups...
Share
Share this post:

[?] Why doesn't Cases[{"a", "b"}, "a"~~___] return {"a"} instead of {}?

Posted 7 years ago

Why doesn't

Cases[{"a", "b"}, "a"~~___] 

return {"a"} instead of {}?

I used three underscores. More detailed, why does 62 work, but 61 not

In Cases[{"abcde", "b"}, "a"~~__]

Out[61]= {}

In[62]:= StringMatchQ["abcde", "a" ~~ __]

Out[62]= True
POSTED BY: Paul Nielan
3 Replies
Posted 7 years ago

Duplicate MMa.SE thread with good discussion on the subject:

POSTED BY: Alexey Popkov

As Neil also said, you are mistaking regular patterns with string patterns. Cases takes a pattern (which can involve strings!), StringMatchQ takes string patterns.

Look at the documentation:

guide/Patterns
tutorial/StringPatterns

In your case you can also use:

Select[{"a", "b"}, StringStartsQ["a"]]
POSTED BY: Sander Huisman

Paul,

You need either

StringCases[{"a", "b"}, "a" ~~ ___]

which returns

{{"a"}, {}}

or

Select[{"ah", "b", "a"}, StringMatchQ["a" ~~ ___]]

which gives what I think you want:

{"ah", "a"}

I do not believe that Cases can take a string pattern. For that you would need to use StringCases.

Regards

POSTED BY: Neil Singer
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract