【问题标题】:Regex of getting rid of punctuations before and after a string摆脱字符串前后标点符号的正则表达式
【发布时间】:2014-10-30 04:32:54
【问题描述】:

有什么方法可以去掉字符串前面和结尾的符号吗?

例如,

"hello," -> "hello"
"hello;" -> "hello"

换句话说,删除单词之后、之前或内部的所有标点符号,除了单引号和单破折号(如果它们后面有更多字母)。

更多示例,

"lies,", "'This", "all-eating" and "deserv'd."

会变成

"lies", "this", "all-eating" and "deserv'd"

【问题讨论】:

  • remove all punctuation after, before, or within a word 提供一个单词内的示例。并且不要忘记展示你的尝试。
  • "lies,", "'This", "all-eating" 和 "deserv'd", 分别指向 "lies", "this", "all-eating" 和 "deserv' d"
  • 预期的输出是什么?在您的问题中添加上述评论。

标签: java regex punctuation


【解决方案1】:

使用 poxix 正则表达式术语\p{Punct}

str = str.replaceAll("^\\p{Punct}*|\\p{Punct}+$|\\p{Punct}{2,}", "")

使用“两个或更多”匹配删除中间词标点符号。


一些测试代码:

for (String str : new String[]{"hello,", "hello;", "li--es", "'This", "all-eating", "deserv'd."})
    System.out.println(str.replaceAll("^\\p{Punct}*|\\p{Punct}+$|\\p{Punct}{2,}", ""));

输出:

hello
hello
lies
This
all-eating
deserv'd

【讨论】:

    猜你喜欢
    • 2020-04-02
    • 1970-01-01
    • 2020-07-15
    • 1970-01-01
    • 2019-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-27
    相关资源
    最近更新 更多