Remove special characters in the string in java?

前端 未结 7 2119
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-15 08:28

How to remove special characters in the string except \"- _\". Now I use:

replaceAll(\"[^\\\\w\\\\s]\", \"\")

it remove all special charact

7条回答
  •  旧巷少年郎
    2021-01-15 09:00

    barely 6 years have passed and we have a lambda solution

    String str = "owl@134_- abc";
    str.codePoints().mapToObj( Character::toChars ).filter(
        a -> (a.length == 1 && (Character.isLetterOrDigit( a[0] ) || a[0] == '-' || a[0] == '_')) )
      .collect( StringBuilder::new, StringBuilder::append, StringBuilder::append ).toString(); // owl134_-abc
    

提交回复
热议问题