The following will remove the punctuation character from the beginning and end of the String object, if any:
String s = "\"New, Delhi\""; // Output: New, Delhi System.out.println(s.replaceAll("^\\p{Punct}|\\p{Punct}$", ""));
The ^ part of the regular expression represents the beginning of the text, and $ denotes the end of the text. Thus, ^\p{Punct} will match the punctuation, which is the first character, and \p{Punct}$ will match the punctuation, which is the last character. I used | (OR) to match either the first expression or the second, resulting in ^\p{Punct}|\p{Punct}$ .
If you want to remove all punctuation from the beginning and end of a String object, you can use the following:
String s = "\"[{New, Delhi}]\""; // Output: New, Delhi System.out.println(s.replaceAll("^\\p{Punct}+|\\p{Punct}+$", ""));
I just added a + sign after each \p{Punct} . The + sign means "One or more", so it will correspond to many punctuation, if they are present at the beginning or end of the text.
Hope this is what you were looking for :)
source share