Remove special characters in the string in java?

泄露秘密 提交于 2019-12-01 11:29:41

Use replaceAll("[^\\w\\s\\-_]", "");

What I did was add the underscore and hyphen to the regular expression. I added a \\ before the hyphen because it also serves for specifying ranges: a-z means all letters between a and z. Escaping it with \\ makes sure it is treated as an hyphen.

This might help:

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

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!

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_-

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

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

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!