elisa
elisa

Reputation: 229

regular expression to match Number + string

I am trying to match these use cases in Javascript:
a) 8 Months
b) 18 Years

Numbers could range from 1 to 20 and the strings could only be either "months" or "years"

I am trying this

[0-9]\s(Years|Months)

But it is not working.

Upvotes: 0

Views: 63

Answers (1)

logi-kal
logi-kal

Reputation: 7880

You can use this:

([1-9]|1[0-9]|20)\s(Years|Months)

where:

  • [1-9] matches a digit from 1 to 9
  • 1[0-9] matches a number from 10 to 19
  • 20 matches just 20

Edit: As noticed in a comment, you should use

^([1-9]|1[0-9]|20)\s(Years|Months)$

if the whole string must exactly match with this text.

Another option is prepending the regex with a word boundary (\b) in order to prevent matching cases like "42 Years".

Upvotes: 3

Related Questions