regex delete heading and tailing punctuation
I am trying to write a regex in Java to get rid of all heading and tailing punctuation characters except for "-"
in a String, however keeping the punctuation within words intact.
I tried to replace the punctuations with
""
,String regex = "[\\p{Punct}+&&[^-]]";
right now, but it will delete the punctuat开发者_Go百科ion within word too.I also tried to match pattern:
String regex = "[(\\w+\\p{Punct}+\\w+)]";
andMatcher.maches()
to match a group, but it gives me null for inputString word = "#(*&wor(&d#)("
I am wondering what is the right way to deal with Regex group matching in this case
Examples:
Input: @)($&word@)($& Output: word
Input: @)($)word@google.com#)(*$&$ Output: word@google.com
Pattern p = Pattern.compile("^\\p{Punct}*(.*?)\\p{Punct}*$");
Matcher m = p.matcher("@)($)word@google.com#)(*$&$");
if (m.matches()) {
System.out.println(m.group(1));
}
To give some more info, the key is to have marks for the beginning and end of the string in the regex (^ and $) and to have the middle part match non-greedily (using *? instead of just *).
精彩评论