0

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.

1
  • Try [0-9]+\s(Years|Months) + will make RE to accept atleast 1 number. Commented May 12, 2021 at 12:36

1 Answer 1

3

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".

Sign up to request clarification or add additional context in comments.

2 Comments

Note that this regex still matches 2 Years in the text 42 Years, depending on the context of OP you (the reader of the answer) might want to anchor the regex to the start ^ and end $ of the string or use a negative lookbehind to make sure the character before the match is not a number.
@3limin4t0r Thank you, I updated the answer mentioning also the word boundary.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.