2

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!

1
  • I don't know much about the exact thing you are asking but if you want each of your string to follow the pattern, a2-a4, d7-d8, you can try trimming the length of the string to only 5 characters. Or, you can get the index of the hyphen(which seems to an important part of your pattern) using indexOf() method and then retrieve the previous two and next two characters using substring() method. Commented Jun 29, 2020 at 16:11

1 Answer 1

1

You can do it as follows:

public class Main {
    public static void main(String[] args) {
        // Test strings
        String[] arr = { "garbo1239%)@a2-a5", "a2-a4d", "h7-h614" };
        for (String str : arr) {
            System.out.println(str.replaceAll(".*?([a-h][1-8]-[a-h][1-8][BQNRbqnr]?).*", "$1"));
        }
    }
}

Output:

a2-a5
a2-a4
h7-h6

Explanation: Replace the given string with group(1) which is represented by $1 where group(1) contains the regex for the desired output and everything before or after it needs to be discarded.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.