Yet Another RegEx Issue

Post your questions and help other users.

Moderator: Martin

Post Reply
Denton
Posts: 2
Joined: 08 Mar 2016 18:39

Yet Another RegEx Issue

Post by Denton » 08 Mar 2016 20:48

I am attempting to extract the date/time from this string: "Last Updated on March 8, 10:46 AM MST"

I am wanting to end up with this string: "March 8, 10:46 AM"


This is what I am using:

Code: Select all

updateList=newList();
updateTimeRaw="Last Updated on March 8, 10:46 AM MST";
matches(updateTimeRaw, '\\w+ \\d{1,2}, \\d{1,2}:\\d{2} \\w{2}', updateList);
updateTime=getElement(updateList, 0);
This is the error generated:
08.03.2016 13:35:04.325 [Get Weather] End executing action 'Script: Weather Info' and exception Error while calling function getElement (Expression: getElement(updateList, 0)[line 11], Cause: Invalid index 0, size is 0)

I am reading this to mean that there are no matches stored in updateList.


The regex that I am using is pretty basic and works a treat in any tester that I have checked it in. I tried breaking it down to see if I could locate where I was going wrong. Changing it to '.*' works as expected and matches the entire string which is returned properly by the getElement function. Changing that to just the first element of the original regex, '\\w+', results in the same error.

Is there some quirk in Automagic that I have missed in my search for answers? I am using single quotes so the contents of the curly brackets are not evaluated. I am escaping the backslashes with another backslash. I have read everything I could find on the forum regarding regex and am coming up blank.

User avatar
Martin
Posts: 4468
Joined: 09 Nov 2012 14:23

Re: Yet Another RegEx Issue

Post by Martin » 09 Mar 2016 19:47

Hi,

I recommend to use the regex tester built into Automagic to ensure that you are not running into some small incompatibility in regex testers. You can find it within action script button 'Regex Tester'.
It also shows the frequently used functions handling regexs in Automagic and helps by escaping the backslashes.

The matches function only returns true when the entire string matches the defined pattern and only then will provide the groups. Group 0 contains the entire match, other groups have to be enclosed in parentheses so your extracted value can be found at index 1.
The following script should work:

Code: Select all

updateList=newList();
updateTimeRaw="Last Updated on March 8, 10:46 AM MST";
matches(updateTimeRaw, '.*?(\\w+ \\d{1,2}, \\d{1,2}:\\d{2} \\w{2}).*', updateList);
updateTime=getElement(updateList, 1);
Regards,
Martin

Denton
Posts: 2
Joined: 08 Mar 2016 18:39

Re: Yet Another RegEx Issue

Post by Denton » 09 Mar 2016 20:03

Ok. That's where I was going wrong. I didn't realize that I had to match the entire string with the regex.

Thank you very much for the help and the awesome app.

Post Reply