简体   繁体   中英

Using Regex to find values in a file

I'm not really looking for syntax help, per say, but approach advice. Here's what I need to do:

I need to read some text in from a file containing moves (this is part of a chess game project) and then print out what move was performed. Here's the example text I'm using for the text file:

EDIT: to clarify, these each represent a move. ie RlA1 means white room moved to A1, NlB1 means white knight to B1, etc.

RlA1 NlB1 BlC1 QlD1 KlE1 BlF1 NlG1 RlH1
PlA2 PlB2 PlC2 PlD2 PlE2 PlF2 PlG2 PlH2
RdA8 NdB8 BdC8 QdD8 KdE8 BdF8 NdG8 RdH8
PdA7 PdB7 PdC7 PdD7 PdE7 PdF7 PdG7 PdH7
B1 C3* B2 B3 D8 H4

and here is what should be output for this example input:

A white rook is placed on A1 and a white knight is placed on B1 ... etc 
A white pawn ... etc 
A black rook ... etc 
A black pawn ... etc 
The piece on B1 moves to C3 and captures the piece there and the piece on B2 moves to B3 and the piece on D8 moves to H4

Obviously I'll use a toString() method override to print the moves back out, but I need to know how I should go about parsing the input with RegEx to determine what each move is.

Again, not really looking for syntax help so much as advice on how I should approach the problem (Pseudo)

I'm doing this in Java.

First, you just want to split the string into the individual moves. Do this by using your language's string split function.

After doing this, you can parse the individual moves. Note though that chess moves can be quite complex in standard notation, so I'd suggest not trying to mash it all into one regexp. Rather, create helper function such as is_capture , is_castle , is_en_passant , get_moving_piece , and so on.

This depends on the language. If its a compiled language i would do as tim suggested, split() and parse one letter at a time.

If its command land, then you can use awk for instance to grab each seperate one, space delimited, then parse one letter at a time again.

Since you are writing a Chess Game project, I suggest formatting your moves file in an easier manner to parse. Put all piece placements on one line. On the next line put the moves with a comma separating each move so something like: B1 C3*, B2 B3, D8 H4, etc.

When you are reading in the file, read in the first line and split it on whitespace. Send each of the resulting array elements to a function that parses piece placement.

Read in the next line and split it on comma. Send each of the resulting array elements to a function that parses the moves. Each element will contain the starting and ending place of the piece so you don't have to do as much crazy parsing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM