开发者

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.

  1. I tried to replace the punctuations with "", String regex = "[\\p{Punct}+&&[^-]]"; right now, but it will delete the punctuat开发者_Go百科ion within word too.

  2. I also tried to match pattern: String regex = "[(\\w+\\p{Punct}+\\w+)]"; and Matcher.maches() to match a group, but it gives me null for input String 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 *).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜