Tschallacka
Tschallacka

Reputation: 28722

Regex to match date with string as month

I have the following string:

var cur = "t+20d";

And I want to match it. That part I already did with

if(cur.match(/^[t]\+[0-9]{2,4}[dmyw]/i))

Now I also need to be able to match this string, and prefably in the same regex

var cur = "10may15+20d";

I have tried

  cur.match(/^([t]|([0-9]{1,2}(jan|feb|march|apr|may|jun|jul|aug|sept|okt|nov|dec)))\+[0-9]{2,4}[dmyw]/i) 

But it doens't work as intended.

if I try to compile the subpart I get two pieces of array instead of one

 cur.match(/[0-9]{1,2}(jan|feb|march|apr|may|jun|jul|aug|sept|okt|nov|dec)/i);
 //yields ["10MaY", "MaY"]

And this worries me about false positives.

I'm really really rusty at regex, last time I tried to make a complicated regex was 15 years ago and that was in perl, so I could really use some help with this one. I know ors and grouped matches are possible, I just can't figure out how to do it anymore so some help is appriciated.

Upvotes: 1

Views: 169

Answers (2)

Tschallacka
Tschallacka

Reputation: 28722

With the help of @AvinashRaj who pointed me to the group operator ?: with his regex I managed to compose this regexfor my uses and i'm posting it here for future users who might need to match a date string like this. ddmmmyy

cur  = "10-apr-1115+20d";
cur.match(/^(?:t|[0-9]{1,2}(?:jan|feb|mar|apr|may|jun|jul|aug|sep|okt|nov|dec|[-\/](?:[0-9]{1,2}|jan|feb|mar|apr|may|jun|jul|aug|sep|okt|nov|dec)[-\/])(?:[0-9]{2}|[0-9]{4}))\+[0-9]{1,4}[dmyw]/igm);

Upvotes: 1

Avinash Raj
Avinash Raj

Reputation: 174706

You need to match the number which exists after the month.

^(t|[0-9]{1,2}(?:jan|feb|march|apr|may|jun|jul|aug|sept|okt|nov|dec)\d+)\+[0-9]{2,4}[dmyw]

DEMO

Upvotes: 1

Related Questions