简体   繁体   中英

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?

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.

maybe this one will work

\d+\w+

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

Try:

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM