Home > front end >  Regex for simple FEN validation
Regex for simple FEN validation

Time:11-30

I'm looking to validate a chess FEN string and I'm working on the Regex for it. I'm looking to implement only very simple validation. Here are the rules I'm looking to match with my regex:

  • Exactly 7 "/" characters
  • Start and end of the string cannot be "/"
  • In between the slashes it must be either a number from 1-8 or the letters PNBRQK uppercase or lowercase

Example of a match
rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR

Examples of non-match
rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR/
/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR/
rnbqkbnr/pppppppp/8/8/8/10/PPPPPPPP/RNBQKBNR
rnbqkbnr/Z/8/8/8/8/PPPPPPPP/RNBQKBNR

Currently, I have been able to implement exactly 7 "/" anywhere in the string with the following regex:

/^(?:[^\/]*\/){7}[^\/]*$/gm

I'm unsure how to implement the rest as RegEx is not my strong suit.

CodePudding user response:

/^([1-8PNBRQK] \/){7}[1-8PNBRQK] $/gim

/gim = global, case insensitive, and multiline.

I got the above working on https://regexr.com/ - one of my favorite places for working out regex problems (but I know there are many other good resources online).

Hope this helps.

CodePudding user response:

This should do the trick: (passes all your tests)

/^(?:(?:[PNBRQK] |[1-8])\/){7}(?:[PNBRQK] |[1-8])$/gim

All you needed was to use positive matching for the characters you're after instead of "not slash". The key addition is the non-capturing group with one or more PNBRQK or a digit from 1-8. The same group is repeated at the end of the expression.

Oh, and I added the i flag for case insensitive matching.

  • Related