How can I remove all leading and trailing punctuation?

前端 未结 3 559
不思量自难忘°
不思量自难忘° 2020-12-11 17:30

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

3条回答
  •  既然无缘
    2020-12-11 17:54

    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.

提交回复
热议问题