1

This is a continuation of the previous thread because none of the answers there produced the intended result. I am getting super wierd behavior using regexes to match dates. I want to match the following dates:

[month-day]

Such as:

"[01-23]" // January 23rd is a valid date
"[02-31]" // February 31st is an invalid date
"[02-16]" // valid
"[ 6-03]" // invalid format

Here is my regex:

regex = /\[^[0-1][1-9]\-[0-3][0-9]\]/

I tried to put both a single \ and double \ infront of brackets but nothing seems to be working for matching these dates. Any ideas?

Thanks!

Community
  • 1
  • 1
chopper draw lion4
  • 12,401
  • 13
  • 53
  • 100

3 Answers3

4

The problem with your regex is the placement of the start-of-line anchor ^ after the initial square bracket. This cannot happen, so your regex never matches anything.

Move the anchor to the beginning of your expression to fix the problem:

regex = /^\[[0-1][1-9]\-[0-3][0-9]\]/
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
2

Put the "start of line" character ^ first:

regex = /^\[[0-1][1-9]-[0-3][0-9]\]/

And you don't need to escape the middle minus - in that context.

bloodyKnuckles
  • 11,551
  • 3
  • 29
  • 37
1

You put the anchor ^ in the wrong place. It has to be in the very front or it'll never match. Moreover, your regex doesn't even work the way you want it to work:

https://regex101.com/r/tV8hH7/1

m0meni
  • 16,006
  • 16
  • 82
  • 141