-3

I need to match one upper case letter followed by optional +/- symbol

eg. The possible matches are A/A+/B/B-/C/C+ ... Z/Z+/Z-

I have tried :

regExp= /^[A-Z][\+,\-]?/;

But this is allowing special characters and double chars as well AA/AB/A$/A# etc

Here first part [A-Z] seems to work properly but second part [\+,\-]? is not working

Girish Gupta
  • 1,241
  • 13
  • 27
  • Add a `$` at the end of your regex? – Ivar Mar 03 '21 at 15:50
  • 2
    You are not using an end string anchor. Also, you don't need to escape those characters nor do you have to seperate them with a comma inside your character class >> `^[A-Z][+-]?$` – JvdV Mar 03 '21 at 15:50

1 Answers1

1

You don't have to escape + in a character class ([...]), and you don't have to escape - at the end of a character class (or the beginning, but you do in the middle and doing so is harmless even when not necessary). Also, you don't separate the characters in a class with commas.

If you only want to match at the start of your input, just remove the escapes and commas: /^[A-Z][+-]?/

If you want to match anywhere in the input, remove the start-of-input anchor: /[A-Z][+-]?/

If you want to match the full input, add an end-of-input anchor: /^[A-Z][+-]?$/

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875