Remove special characters in the string in java?

前端 未结 7 2105
爱一瞬间的悲伤
爱一瞬间的悲伤 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 08:41
    Pattern pt = Pattern.compile("[^a-zA-Z0-9_-]");
        Matcher match = pt.matcher(c);
        while (match.find()) {
            String s = match.group();
            c = c.replaceAll("\\" + s, "");
        }
    

    Consider this

    0 讨论(0)
  • 2021-01-15 08:44

    Use this replaceAll("[\\w\\s\\-\\_\\<.*?>]", "") ;

    0 讨论(0)
  • 2021-01-15 08:56

    I suspect that you need to assign the result (in case you're not doing that), because replaceAll() returns a new string, rather than updating the string (String is immutable):

    str = str.replaceAll("[^\\w\\s-]", "");
    

    Also note that the regex is quite simple:

    No need to escape the dash - in the character class: When used as a literal in a character class, it must be either first or last (otherwise it indicates a range, like a-z etc).

    No need to mention the underscore at all, because it is already listed: \w includes the underscore character!

    0 讨论(0)
  • 2021-01-15 08:57
    String str="owl@134_- abc";
    String s=str.replaceAll(" [^a-zA-Z_-]+ ", "");
    System.out.println(str);
    

    It will replace the special character and white spaces from a given string.

    Output will be: owlabc_-

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-01-15 09:03

    This might help:

    replaceAll("[^a-zA-Z0-9_-]", "");

    0 讨论(0)
提交回复
热议问题