RedGuts
RedGuts

Reputation: 83

Regex date pattern matching

I am novice in regex. Like to know the below date pattern.

(\\d{2}(0[1-9]|1[012]|[0]{2}))

I just know,

Upvotes: 1

Views: 622

Answers (1)

arshajii
arshajii

Reputation: 129487

\d is a predefined character class that is generally equivalent to [0-9] (sometimes it also includes unicode digits, depending on the regex engine). Moreover, {n} is a quantifier, and X{n} matches X exactly n times. Therefore, \d{2} matches 2 consecutive digits.

Also, [0]{2} is 2 consecutive 0s: 00 (not 0000).

You're also slightly off about 0[1-9]: it matches any of 01, 02, ..., 09 (1 can't be at the start). You're correct about 1[012].

Overall, this is what your regex looks like:

Regular expression visualization

If you want to read more about them, a great online reference regarding regular expressions is regular-expressions.info.


Note that in the above answer I've assumed you mean \d by \\d, and have used the latter because you're representing the regex in a string format that requires \s to be escaped. When representing generic regexes, however, it's best to leave \s unescaped. In other words, \\d might be interpreted as a literal backslash followed by a d, so \\d{4} would match \dddd. Presumably this isn't what you mean;

Upvotes: 8

Related Questions