3

I'm looking to validate a string that has any number of digits followed by a specific character, for example:

"1w 3d 5h 3m" and "32d 5h 3m"

I'm using the following regex at the moment: /\d+[wdhm]\z/ but this is not working if a string contains a letter that I don't want, for example:

"3pp 2h 35m" and "2d 5qq 3m"

The only allowed letters in the string can be "w", "d", "h" and "m" and must be in that order if once is present, for example "2d 35m" is acceptable but "3h 1w" is not because it's in the wrong order.

1
  • Try ^(\d+w )?(\d+d )?(\d+h )?(\d+m)$ Commented Jun 13, 2021 at 11:31

1 Answer 1

4

You may use this regex with multiple optional matches and a lookahead:

^(?=\d)(?:\d+w\h*)?(?:\d+d\h*)?(?:\d+h\h*)?(?:\d+m)?$

RegEx Demo

RegEx Details:

  • ^: Start
  • (?=\d): Lookahead to assert presence of a digit to disallow empty matches
  • (?:\d+w\h*)?: Match 1+ digits followed by w and 0+ whitespaces
  • (?:\d+d\h*)?: Match 1+ digits followed by d and 0+ whitespaces
  • (?:\d+h\h*)?: Match 1+ digits followed by h and 0+ whitespaces
  • (?:\d+m)?: Match 1+ digits followed by m
  • $: End

If you don't want to allow zero spacing between components then use:

^(?=\d)(?:\d+w\h*)?(?:\b\d+d\h*)?(?:\b\d+h\h*)?(?:\b\d+m)?$

RegEx Demo 2

If you want to allow only single spacing then use:

^(?=\d)(?:\d+w\h)?(?:\b\d+d\h)?(?:\b\d+h\h)?(?:\b\d+m)?$

RegEx Demo 3

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.