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]$/
CodePudding user response:
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 anHchar(?:(\d )M)?- an optional group matching one or more digits (captured into Group 2) and then anMchar(?:(\d )S)?- an optional group matching one or more digits (captured into Group 3) and then anSchar$- end of string.
