Stevie Star
Stevie Star

Reputation: 2371

Javascript - how do I check regex to ensure a string contains at least one sequence of letters/numbers?

I'm trying to figure out the correct regex for detecting a pattern that looks something like 2d1h30m10s where any of them are valid, such as 1h or 1h30m or 30m or 10s or any combination of those. Is regex the right tool here?

I'm trying to understand it and no matter what I do, I keep getting false back from the these different tests:

/^(0?[1-9]|1[0-2][h])([1-6][0-9][m])([1-6][0-9][s])\d$/.test('2d1h10m10s')
/^(0?[1-9]|1[0-2][h])([1-6][0-9][m])([1-6][0-9][s])\d$/.test('10m10s')
/^(0?[1-9]|1[0-2][h])([1-6][0-9][m])([1-6][0-9][s])\d$/.test('10s')

What am I missing here?

Upvotes: 0

Views: 60

Answers (4)

Barmar
Barmar

Reputation: 780673

You need to make each section of the regexp optional, so you can omit that unit.

You need to take [h] out of one of the alternatives -- you match 12h but not 01h.

You shouldn't have \d at the end.

You're not allowing single-digit minutes or seconds. There's also no need for 60s or 60m, since that's 1m and 1h.

/^((0?[1-9]|1[0-2])h)?([1-5]?[0-9]m)?([1-5]?[0-9]s)?$/

DEMO

There's no need to put h, m, and s inside square brackets, since they're just single characters.

Note that since each unit is optional, this will also match an empty string. You should check for this separately from the regexp.

Upvotes: 1

do or do not
do or do not

Reputation: 156

I think the expression you're looking for is :

/^((0?[1-9]|1[0-2])h)?((([0-5]?[0-9])|60)m)?((([0-5]?[0-9])|60)s)?$/

Your original expression has two primary problems : 1. the \d at the end, and 2. capturing scope (note the extra parens in my expression).

This will also capture : 1h13s

Upvotes: 0

Thomas Skubicki
Thomas Skubicki

Reputation: 637

Try:

^(\d{0,2}[hms]){0,3}$

examples: https://regex101.com/r/NV6oEu/1

Upvotes: 0

duc mai
duc mai

Reputation: 1422

maybe this one will work

\d+\w+

If I understand you correctly that you are trying to test a string contain characters following numbers

Upvotes: 0

Related Questions