Home > Software engineering >  RegEx to match exactly one occurrence of character at the end of string in Javascript
RegEx to match exactly one occurrence of character at the end of string in Javascript

Time:06-11

I have a string and want to match pattern which has either s or m at the end of string having only one occurrence. I haven't used regex much and unable to find any answers.
E.g. If the string is 121ss. It should return false. 121s and 121m should return true. 121ms should also return false. It is also case sensitive so 121M or 121H won't do.
The pattern I tried using is /[mh]{1}$/

CodePudding user response:

If "m" and "s" must be preceded by at least one or more numbers \d use:

/\d [ms]$/

Demo on Regex101

1m      // matches
123m    // matches
1s      // matches
123s    // matches
121ss
121ms
1M
1S
123MS
xyzn
xyzs

PS: if you already use [ms] (meaning "m or s") then the {1} is unnecessary since it matches only one option.

CodePudding user response:

The last character must be m or s, and the next to last character must not be either of them:

/[^ms][ms]$/

You can try this on RegExr, which is a playground with very helpful hints

  • Related