-1

I am trying to find an solution to return a true value if certain expression B which follows expression A is valid.

For instance -

If I'm trying to match the strings with the regex - F[A-Z]{0,2}

F
FA
FB
FAA
FAAA

where F is expression A here and [A-Z]{0,2} is expression B here

It is matching FAAA which it shouldn't since I have mentioned an quantifier max limit to 2.

So the expected output is -

F
FA
FB
FAA

JSFiddle

Kunal Mukherjee
  • 5,775
  • 3
  • 25
  • 53

3 Answers3

2

You need to either use:

\bF[A-Z]{0,2}\b

or

^F[A-Z]{0,2}$

you get true currently because a match does occur. You need some sort of limitation on the matching.

F[A-Z]{0,2} says match an F then 0 to 2 uppercase alpha characters. Anything before or after that can still exist.

See https://regex101.com/r/KLKTS4/2/ for a demo.

user3783243
  • 5,368
  • 5
  • 22
  • 41
1

Adding a $ to the end of your regex should fix it:

F[A-Z]{0,2}$

https://regex101.com/r/1ADic0/2

The $ sign will make sure that you are at the end of line. You can see a lot of regexps starting with ^ and ending with $ (or \A and \z for multiline). This pattern basically means: my regexp should match the whole string.

Ulysse BN
  • 10,116
  • 7
  • 54
  • 82
0

You need to use $ in the end to asserts position at the end of a line and also need to put ^ to asserts position at the start of a line, so that values like BFA, BF could also be ignored. So the update regex would be like:

^F[A-Z]{0,2}$

DEMO

palaѕн
  • 72,112
  • 17
  • 116
  • 136