简体   繁体   中英

regular expression javascript numbers and letters

I can't for the life of me seem to figure out how to set a regular expression of an element with the formatting.

1d 5h 6m 12s

And also allow it to have any variation of those such as

1d 

1d 1h

1d 1h 1m 

1d 1s

6m 12s 

etc...

Is it possible with regular expressions to do that tyle of formatting?

Assuming you need it to be order,

if (/^\s*(?:(?:[1-9]\d*|0)d\s+)?(?:(?:1?\d|2[0-3])h\s+)?(?:[1-5]?\dm\s+)?(?:[1-5]?\ds)?\s*$/.test(str))
{
    // success
}

Here's a quick breakdown:

  1. The ^ and $ are known as anchors . They match the beginning and end of a string, so you're matching the entire string, not only a part, eg hello, world! 1d 5h 6m 12s hello, world! 1d 5h 6m 12s would pass otherwise.

  2. The \\s* and \\s+ match zero or more, and one or more, whitespace characters.

  3. The (?:[1-9]\\d*|0) matches an arbitrary number of digits but not one that start with zero, unless it's exactly zero.

  4. The (?:1?\\d|2[0-3]) matches the digits between 0 and 23, inclusive.

  5. The [1-5]?\\d matches the digits between 0 and 59, inclusive.

  6. The (?: ... ) are known as non-capturing groups . They're like parentheses (for grouping) except that plain ol' parentheses capture , and we don't need that here.

  7. The ? means the preceding entity is optional.

To give you a starting point:

(\d+d){0,1} //days - not checking for a max

(((([0-1]){0,1}\d)|(2[0-4]))h){0,1} // 24 hours

(((([0-5]){0,1}[0-9])|(60))m){0,1} //60 minutes

(((([0-5]){0,1}[0-9])|(60))s){0,1} //60 seconds

Then put them all together (in this case not worrying about amount of whitespace)

(\d+d){0,1}[ ]*(((([0-1]){0,1}\d)|(2[0-4]))h){0,1}[ ]*(((([0-5]){0,1}[0-9])|(60))m){0,1}[ ]*(((([0-5]){0,1}[0-9])|(60))s){0,1}[ ]*

Including @nhahtdh 's improved version of the above from the comments. Thanks!

((\d+)d)? *(([01]?\d|2[0-4])h)? *(([0-5]?\d|60)m)? *(([0-5]?\d|60)s)? *

I think this is what you want:

function parse(s) {
 y = s.match(/(?:(\d+)d\s*)?(?:(\d+)h\s*)?(?:(\d+)m\s*)?(?:(\d+)s)?/);
 console.log(y);
 return y;
}

Here's how it works:

  • (\\d+)d\\s* matches some digits followed by a d , followed by optional whitespace
  • wrapping it in (?:...)? , like (?:(\\d+)d\\s*)? makes the above optional. The ?: causes the new set of parentheses to not be a capturing group.
  • repeat for h, m and s and you're done.

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