Java Regex for Chess notations I have this regex:

(\d?)[A-Za-z](?=(\d?)(.*))(?=(.* ){5})


It would be used by me for Chess FEN strings.

I wonder if regex [A-Za-z] is faster than [RNBQKrnbqk]? I only need to check the given letters (but no other letters will appear).

My thoughts are:


[A-Za-z] - the regex engine can match if a char is 65 &lt;= c &lt;= 90 or 97 &lt;= c &lt;= 122. Worst case is 4 comparisons.
[RNBQKrnbqk] - the engine checks if the inspected char equals every given character in the group. Worst case is 10 comparisons.


Am I understanding regex correctly?
No. The matching for a-zA-Z would be slower than the exact character-set you supply: RNBQKrnbqk.

You can observe this behaviour by checking the backtrace it generates. I compared 3 different patterns, two being your own, and the third I found on chess.stackexchange.com:

(\d?)[a-z](?=(\d?)(.*))(?=(.* ){5})


has 64 matches generated in 14323 steps

(\d?)[rnbqk](?=(\d?)(.*))(?=(.* ){5})


has 32 matches generated in 7512 steps

and the pattern from chess.stackexchange:

([rnbqkp1-8]+\/){7}([rnbqkp1-8]+)\s[bw]\s(-|K?Q?k?q?)\s(-|[a-h][36])


has 2 matches generated in 95 steps



Note that I have enabled the ignorecase flag in all three of them.