Regular expression sequence starting with a number followed by uppercase HMS

Viewed 35

I'm trying to write a regular expression to match a sequence that starts with a number [0-9] followed by only one uppercase [HMS].

For example the following should match, 10H, 10H20M, 10H20M9S, 20M, 5H6S. Lowercase letters are not allowed. Only H,M,S after any number between [0-9].

These should fail ( 3Y5M, 5H4F, 10H6MM ).

I tried this but it doesn't work :(

^[0-9][HMS]$/
1 Answers

You can use

^(?!$)(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?$

See the regex demo.

Details:

  • ^ - start of string
  • (?!$) - the string can't be empty
  • (?:(\d+)H)? - an optional group matching one or more digits (captured into Group 1) and then an H char
  • (?:(\d+)M)? - an optional group matching one or more digits (captured into Group 2) and then an M char
  • (?:(\d+)S)? - an optional group matching one or more digits (captured into Group 3) and then an S char
  • $ - end of string.
Related