Alex Cory
Alex Cory

Reputation: 11865

Regex to match "maybe valid month"

Basically I want to match the following:

const regex = /(?=.*[0-1])(?=.*[^0{2}])|(0[1-9]|1[012])$/
console.log('0, should be True: ', regex.test('0'))
console.log('1, should be True: ', regex.test('1'))
console.log('00, should be False: ', regex.test('00'))
console.log('01, should be True: ', regex.test('01'))
console.log('12, should be True: ', regex.test('12'))
console.log('99, should be False: ', regex.test('99'))

Valid: 0, 1, 01-09, 10-12 Invalid: 00, >12

Anyone know how to do this?

Upvotes: 1

Views: 67

Answers (3)

Malik Tauqeer
Malik Tauqeer

Reputation: 7

You can do something like this.

var regex = /^\d?$|^0[1-9]?$|^1(=?[0-2])$/;

or:

var regex = /^\d?$|^0[1-9]?$|^1[0-2]$/;

or:

var regex = /^(\d?|^0[1-9]?|^1[0-2])$/;

there are many possible way you can achieve the same results.

Upvotes: 0

janos
janos

Reputation: 124646

This will do:

const regex = /^([01]|0[1-9]|1[012])$/;

That is, either of:

  • Single digit 0 or 1
  • 0 followed by single digit 1 .. 9
  • 1 followed by 0, 1 or 2

Output of your tests:

0, should be True:  true
1, should be True:  true
00, should be False:  false
01, should be True:  true
12, should be True:  true
99, should be False:  false

Upvotes: 1

Derek 朕會功夫
Derek 朕會功夫

Reputation: 94319

This will do:

/^0[1-9]|[0-9]|1[0-2]$/

Upvotes: 0

Related Questions