MOVE ( new MoveToken() ),
COMMENT ( new CommentToken() ),
- VARIATION ( new VariationToken() );
+ VARIATION ( new VariationToken() ),
+ RESULT ( new ResultToken() );
private Token<Moves> token;
private static final String MOVES_REGEX = "^\\s*([^\\s])";
private static final Pattern MOVES_PATTERN = Pattern.compile(MOVES_REGEX);
+ private static final String RESULT_REGEX = "^\\s*(1-0|0-1|1/2-1/2|\\*)";
+ private static final Pattern RESULT_PATTERN = Pattern.compile(RESULT_REGEX);
+
private static final String COMMENT = "{";
private static final String VARIATION = "(";
@Override
public int token(Entity entity, String pgn) throws ParseException {
int pgnLength = pgn.length();
- pgn = PGNUtils.stripCrlf(pgn);
- Token<Moves> token = assignToken(pgn);
- while (token != null) {
- int index = token.token(entity, pgn);
+ pgn = PGNUtils.stripCrlf(pgn); // todo: starting with ";" comments
+ boolean isResulted = false;
+ Type tokenType = tokenType(pgn);
+ while (tokenType != null) {
+ if (isResulted) {
+ throw new ParseException("parse.pgn.symbols.after.result", pgn);
+ }
+ int index = tokenType.token().token(entity, pgn);
+ if (tokenType.equals(Type.RESULT)) isResulted = true;
pgn = pgn.substring(index);
- token = assignToken(pgn);
+ tokenType = tokenType(pgn);
}
return pgnLength;
}
- private Token<Moves> assignToken(String pgn) {
- Token<Moves> token = null;
- Matcher moveMatcher = MOVES_PATTERN.matcher(pgn);
- if (moveMatcher.find()) {
- switch (moveMatcher.group(1)) {
- case COMMENT:
- token = Type.COMMENT.token();
- break;
- case VARIATION:
- token = Type.VARIATION.token();
- break;
- default:
- token = Type.MOVE.token();
+ private Type tokenType(String pgn) {
+ Type type = null;
+ if (RESULT_PATTERN.matcher(pgn).find()) {
+ type = Type.RESULT;
+ } else {
+ Matcher moveMatcher = MOVES_PATTERN.matcher(pgn);
+ if (moveMatcher.find()) {
+ switch (moveMatcher.group(1)) {
+ case COMMENT:
+ type = Type.COMMENT;
+ break;
+ case VARIATION:
+ type = Type.VARIATION;
+ break;
+ default:
+ type = Type.MOVE;
+ }
}
}
- return token;
+ return type;
}
}