Message Boards Message Boards

0
|
7928 Views
|
2 Replies
|
1 Total Likes
View groups...
Share
Share this post:

Why Doesn't DatePattern Work with Position?

Posted 9 years ago

Hi everyone,

I have a list of strings called myStrings, and there is exactly one element containing "7 November 2009".

I can pick off that element using StringMatchQ as

StringMatchQ[myStrings, 
 DatePattern[{"DayShort", " ", "MonthName", " ", "Year"}]]

But if I use Position

Position[myStrings, 
 DatePattern[{"DayShort", " ", "MonthName", " ", "Year"}]]

it returns {}. What am I doing wrong?

Gregory

POSTED BY: Gregory Lypny
2 Replies
Posted 9 years ago

Hi Gregory,

I am not sure to understand either why it returns an empty list. Perhaps when using strings as list elements in Position, one should use a different pattern construction. But I am not sure why this would be the case, so I do not know. I would be interested if anyone has an idea.

Here is a way that seems to solve the issue. It is not very nice but it works fine:

Position[myStrings, 
        _?(StringMatchQ[#, DatePattern[{"DayShort", "MonthName", "Year"}, " "]] &), Heads -> False]

The Heads -> False avoids Position to test the head of myStrings, which would result otherwise in a warning from StringMatchQ.

Regards, Xavier

POSTED BY: Xavier Roy
Posted 9 years ago

Hi Xavier,

Thank you for the tip.

I don't think Heads->False is needed because Position acts on lists. StringMatchQ will return an error if any element in the list myStrings is not a string. I have been using the following, which works on lists and lists of lists that may also contain data types other than strings.

Position[myStrings, _String?(StringMatchQ[#, DatePattern[{"DayShort", " ", "MonthName", " ", "Year"}]] &)]

The only problem is that the test _String? can slow it down considerably if used repeatedly. I suppose another way to do it would be to convert all of the elements of myStrings to strings using ToString as a precaution.

Gregory

POSTED BY: Gregory Lypny
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