I want to remove all the leading and trailing punctuation in a string. How can I do this?
Basically, I want to preserve punctuation in between words, and I need to r
You could use a regular expression:
private static final Pattern PATTERN =
Pattern.compile("^\\p{Punct}*(.*?)\\p{Punct}*$");
public static String trimPunctuation(String s) {
Matcher m = PATTERN.matcher(s);
m.find();
return m.group(1);
}
The boundary matchers ^
and $
ensure the whole input is matched.
A dot .
matches any single character.
A star *
means "match the preceding thing zero or more times".
The parentheses ()
define a capturing group whose value is retrieved by calling Matcher.group(1)
.
The ?
in (.*?)
means you want the match to be non-greedy, otherwise the trailing punctuation would be included in the group.