mircea .
mircea .

Reputation: 241

Regular expression for year sequence

So I'm trying to match something like

2011,2012,2013

or

2011,

or

2011 

but NOT:

2011,201 or 2011,201,2012

I tried with ([0-9]{4},?([0-9]{4},?)*) but if the first year is matched, it does not consider the rest .

Upvotes: 2

Views: 887

Answers (4)

Chriszuma
Chriszuma

Reputation: 4558

You were close.

 ^[0-9]{4}(?:,[0-9]{4})*,?$

That will match any string consisting of a repeating sequence of 4-digit numbers and commas.

The ^ and $ match the beginning and end of the string, respectively. Thus, it will only match if the string consists of only those elements.

The (?:) is a non-capture group. It allows you to create repeating groups without storing all of them into variables.

EDIT: Forgot about the optional comma at the end. Added a ,? to take care of it.

EDIT 2: At FailedDev's advice, here was my original idea. It also works, but I think it is harder to understand. It is more clever, but that's not always a good thing.

^(:?[0-9]{4}(?:,|$))+$

Upvotes: 4

6502
6502

Reputation: 114569

This will do the trick...

 /^[0-9]{4}(,[0-9]{4})*,?$/

i.e. 4 digits followed by zero or more of (a comma followed by 4 digits) and optionally a last (bad looking) comma before the end.

The first ^ and last $ chars ensure that nothing else can be present in the string.

Upvotes: 1

Marshall
Marshall

Reputation: 4766

/^(?:\d{4},?)*$/

Checks for four digits, each possibly followed by a comma, 0 to many times

Upvotes: 0

FailedDev
FailedDev

Reputation: 26930

if (subject.match(/^\d{4}(?:,?|(?:,\d{4}))+$/)) {
    // Successful match
}

This should work.

Explanation :

"^" +              // Assert position at the beginning of the string
"\\d" +             // Match a single digit 0..9
   "{4}" +            // Exactly 4 times
"(?:" +            // Match the regular expression below
   "|" +              // Match either the regular expression below (attempting the next alternative only if this one fails)
      "," +              // Match the character “,” literally
         "?" +              // Between zero and one times, as many times as possible, giving back as needed (greedy)
   "|" +              // Or match regular expression number 2 below (the entire group fails if this one fails to match)
      "(?:" +            // Match the regular expression below
         "," +              // Match the character “,” literally
         "\\d" +             // Match a single digit 0..9
            "{4}" +            // Exactly 4 times
      ")" +
")+" +             // Between one and unlimited times, as many times as possible, giving back as needed (greedy)
"$"                // Assert position at the end of the string (or before the line break at the end of the string, if any)

Upvotes: 1

Related Questions