Remove special characters in the string in java?

2019-05-28 01:25发布

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

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

it remove all special character but i want to keep "- _" . Can anyone tell me how should I do?

6条回答
▲ chillily
2楼-- · 2019-05-28 01:45

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.

查看更多
聊天终结者
3楼-- · 2019-05-28 01:50

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

查看更多
戒情不戒烟
4楼-- · 2019-05-28 01:52
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_-

查看更多
可以哭但决不认输i
5楼-- · 2019-05-28 01:58

This might help:

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

查看更多
相关推荐>>
6楼-- · 2019-05-28 02:04

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!

查看更多
神经病院院长
7楼-- · 2019-05-28 02:10
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

查看更多
登录 后发表回答