Reputation: 6541
Examples:
// A B C. -> A B C
// !A B C! -> !A B C
// A? B?? C??? -> A? B?? C
Here's what I have so far:
while (endsWithRegex(word, "\\p{P}")) {
word = word.substring(0, word.length() - 1);
}
public static boolean endsWithRegex(String word, String regex) {
return word != null && !word.isEmpty() &&
word.substring(word.length() - 1).replaceAll(regex, "").isEmpty();
}
This current solution works, but since it's already calling String.replaceAll
within endsWithRegex
, we should be able to do something like this:
word = word.replaceAll(/* regex */, "");
Any advice?
Upvotes: 13
Views: 8154
Reputation: 626754
I suggest using
\s*\p{Punct}+\s*$
It will match optional whitespace and punctuation at the end of the string.
If you do not care about the whitespace, just use \p{Punct}+$
.
Do not forget that in Java strings, backslashes should be doubled to denote literal backslashes (that must be used as regex escape symbols).
String word = "!Words word! ";
word = word.replaceAll("\\s*\\p{Punct}+\\s*$", "");
System.out.println(word); // => !Words word
Upvotes: 7
Reputation: 2006
I have modified the logic of your method
public static boolean endsWithRegex(String word, String regex) {
return word != null && !word.isEmpty() && word.matches(regex);
}
and your regex is : regex = ".*[^a-zA-Z]$";
Upvotes: 0
Reputation: 8008
how about this, if you can take a minor hit in efficiency.
reverse the input string
keep removing characters until you hit an alphabet
reverse the string and return
Upvotes: 0
Reputation: 785108
You can use:
str = str.replaceFirst("\\p{P}+$", "");
To include space also:
str = str.replaceFirst("[\\p{Space}\\p{P}]+$", "")
Upvotes: 1