1

I get a string which size is 16 (location of chess pieces on the mini-chess-board). This string may contain only symbols:

  1. K (king)
  2. P (pawn)
  3. N(knight)
  4. R(rook)
  5. B(bishop)
  6. Q (queen)
  7. and whitespaces (free field).

How can i validate this string with regex to check if string size is really 16, symbols are only of these and also it should necessarily contain one K symbol (because one King should be)

I tried [KQBNRP ]{16} but now cant check for a K symbol

Thank you

Neighbourhood
  • 166
  • 3
  • 13

1 Answers1

1

As you know exactly which chars are allowed, you could use a single positive lookahead assertion for a single occurrence of K

Then match any of the listed 16 times using your pattern [KQBNRP ]{16}

^(?=[QBNRP ]*K[QBNRP ]*$)[KQBNRP ]{16}$

Regex demo

Explanation

  • ^ Start of string
  • (?= Positive lookahead, assert that form the current position what is on the right is
    • [QBNRP ]*K[QBNRP ]*$ Match a K between what is in the character class except for the K
  • ) Close the group
  • [KQBNRP ]{16} Match 16 times any of the listed
  • $ End of string
The fourth bird
  • 154,723
  • 16
  • 55
  • 70