Reputation: 23
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!
Upvotes: 2
Views: 53
Reputation: 79425
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.
Upvotes: 1