Skip to content

Instantly share code, notes, and snippets.

@ericdorsey
Created February 16, 2020 06:21
Show Gist options
  • Save ericdorsey/e0523263f9eca33efa088a09d68528d4 to your computer and use it in GitHub Desktop.
Save ericdorsey/e0523263f9eca33efa088a09d68528d4 to your computer and use it in GitHub Desktop.
Parse a Chess.com PGN w/ Vim Regex

Parse A Chess.com PGN With Vim Regex

Copy only the moves part of a Chess.com PGN, including the game result into Vim:

1. e4 {[%clk 0:02:59.9]} 1... e5 {[%clk 0:02:55.1]} 2. Nf3 {[%clk 0:02:58.7]}
2... Nc6 {[%clk 0:02:53.6]} 3. Bb5 {[%clk 0:02:57.1]} 3... a6 {[%clk 0:02:51.3]}
                ... // SNIP // ...
0:00:04.4]} 49. Kf4 {[%clk 0:00:01.3]} 49... g5+ {[%clk 0:00:03.9]} 50. Kf5
{[%clk 0:00:00.4]} 50... Bd3+ {[%clk 0:00:03.4]} 0-1

Get Rid Of Newlines in the Pasted PGN

So we can modfiy the whole PGN as one line

:1,36 s/\n//g

Capture Only The Move Number + White's Move + Black's Move and Game Result

Note that the ^M's below are Vim Newlines; generate with + Enter

:%s/\v%(\s?(\d+\.)\s?(\w+\+?\-?\w?)\s?\{[^}]*\}\s?\d+\.{3}\s?(\w+\-?\w?\+?)|(\d+\.)\s(\w+\+?))\s?\{[^}]*\}\s?(\d\-\d)?/\1 \2 \3 ^M\4 \5 ^M\6/g

Get Rid of Blank Lines Followed By Newlines

Extra blank lines and newlines result from the backrefernce pasting above, but this seems to be the cleanest way to clean them up

:g/\v^\s+\n/d

Result

End up with only the move numbers, white and blacks move per turn, and the game result, all on their own lines

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment