user3801109
user3801109

Reputation: 153

Regex to validate custom alphanumeric string

I need a Regex expression to validate number of years or days or months.

1d or 1 d or 1 day etc. to parse number of days

Or 1-y or 1.5 year etc. to parse years. or 2 m , 2 months etc. for months.

I won't be a combination of different units like 1 year 3 months, so that is not to worry about.

Here is the Regex that I have built so far to parse days.

\b([0-9]{1,4}[-.\s](d|day)?)\b

The problem is it is also matching numberic values like 555. , 98. etc.

What is missing & should it be?

Upvotes: 0

Views: 50

Answers (1)

Barmar
Barmar

Reputation: 782498

Try:

\b\d{1,4}(?:\.\d)?(?:-|\s*)(?:d|days?|m|months?|y|years?)\b

This allows exactly 1 digit after the optional decimal point. If you want to allow more, you can add a quantifier there.

DEMO

Upvotes: 2

Related Questions