lundi 29 juin 2020

Java Regex Matching Classes inside Classes

Hey so I already searched the internet for various examples but I cannot get to work the following Regex. I am trying to remove every char out of a String list entry that doesn't match my pattern.

My pattern looks like this for example: e2-e4, d4-d5 and occasionally a specific last char may be given.

First of every line gets filtered with the following pattern:

List<String> lines = Files.readAllLines(Paths.get(String.valueOf(file)));
        Pattern pattern = Pattern.compile("[a-h][1-8]-[a-h][1-8][BQNRbqnr]?");
        List<String> filteredLines = lines.stream().filter(pattern.asPredicate()).collect(Collectors.toList());

But if I have input like this garbo1239%)@a2-a5, I want the garbo to be filtered out.

I came up with the following solution to this problem: I iterate over my String list and use the replaceAll method to filter out the junk:

for(int i = 0; i < filteredLines.size(); i++){
            filteredLines.set(i, filteredLines.get(i).replaceAll("[^[a-h][1-8]-[a-h][1-8]][BQNRbqnr]?",""));
        }

Unfortunately it doesn't have the desired effect. Things like a2-a4d or h7-h614 are still not being "cleaned" and I couldn't really figure out why. I hope someone can help me, thanks in advance!

Aucun commentaire:

Enregistrer un commentaire