0

I'm almost there but not quite. I've done some looking around but while there are similar questions out there, this is as much about a single regex covering multiple scenarios as it is about the regex semantics of achieving tasks a, b or c etc.

I'm trying to construct a regex which allows either a single number or two numbers or any number of white spaces or an empty string. These are sent from an input field.

/[0-9]{1,2}|\s*/ very nearly does it except it accepts a number followed by a letter so '3r' would be a match.

/[0-9]?\d|\s*/ has the same effect.

I'm very new to this and suspect I'm missing something basic. Anyone have any ideas?

Thanks

Stef
  • 359
  • 1
  • 4
  • 21
  • 1
    With anchors `^(?:[0-9]{1,2}|\s*)$` – The fourth bird Nov 08 '22 at 15:54
  • `^` and `$` are regex symbols you are probably looking for here, those match the star-of-line and end-of-line respectively, so for example adding `^` at the beginning ensures that the next symbol matched by your regex must also be the first character in the tested string. – ncpa0cpl Nov 08 '22 at 15:55
  • Bingo! Thanks very much to both of you. I have *much* to learn :-) – Stef Nov 08 '22 at 15:57
  • Why not trimming the value and then just doing the check for either an empty string or just maximum 2 digits? ... `value = value.trim(); const isValid = (value === '') || (/^\d{1,2}$/).test(value);` ... not everything that can be solved with regex necessarily has to be solved by it. – Peter Seliger Nov 08 '22 at 16:38

0 Answers0