Reputation: 285
I need to remove some characters at the end of a certain list of item. These characters are always the same (C, CD, PDF, CPDF, M) and with this regular expression I'm able to get rid of them :
str.replaceAll("(C|CD|PDF|CPDF|M)$", "");
However, I'm not able to inverse this expression : I'd like to be able to isolate (by removing the rest of the string, for exemple) any of these code, if they're at the end of the string. I tried this :
str.replaceAll("!(C|CD|PDF|CPDF|M)$", "");
I probably get by using some string functions, but I'm sure it's possible using only regular expression.
Upvotes: 1
Views: 342
Reputation: 4159
Same as Josh Hight, except for the regexp that allow to get both parts
Matcher m = Pattern.compile("(.*)(C|CD|PDF|CPDF|M)$").matcher("165N1JCD");
while (m.find()) {
System.out.println(m.group(1)); // prints out "165N1J"
System.out.println(m.group(2)); // prints out "CD"
}
Upvotes: 2
Reputation: 55864
If you don't want to use the Matcher class, you can stick with replaceAll:
str.replaceAll(".*(C|CD|PDF|CPDF|M)$", "$1");
Upvotes: 0
Reputation: 17321
You can use the Matcher class to grab a specific group (the suffix you remove) and perform the replaceAll operation. Another option would be to make your expression have two groups, the one you have and one before it for everything else.
Upvotes: 0
Reputation:
You're already using parenthesis to capture the matching group, now simply reference that group.
Matcher m = Pattern.compile("(C|CD|PDF|CPDF|M)$").matcher("165N1JCD");
while (m.find()) {
System.out.println(m.group(1)); // prints out "CD"
}
Upvotes: 5