Loading...

Regex Matching for string pattern


I have a data which is in the following form

5yrs 4mon 

The mon part can vary from 1-12. I need help in writing a regex to extract the numeric value for mon. If for example the input is 5yrs 4mon I would like a regex which returns 4.

- - Source

Answers

answered 1 week ago Ildar Akhmetov #1

The regex you're looking for is quite simple:

\d+yrs\s(\d+)mon

Explanation:

\d+ - one or more digits

\s\ - one space character

(\d+) - one or more digits, it's a capturing group that will have the value you're looking for.

If you need to validate the number and make sure it's exactly 1 to 12, there is a more advanced option:

\d+yrs\s(1?[0-2]|\d)mon

In this case, 13mon will be invalid, for example.

comments powered by Disqus