从 JAVA 中的字符串中去除/删除特定字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13172675/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 11:45:27  来源:igfitidea点击:

strip/remove specific character from string in JAVA

javastringcharacterremoveall

提问by AJJ

i have a string variable say 'result'. The value of this string should contain only alphabets, numerics, dot, space, hyphen and underscore. The regular expression i arrived at is '^[a-zA-Z][a-zA-z ._-]'.

我有一个字符串变量说“结果”。此字符串的值应仅包含字母、数字、点、空格、连字符和下划线。我得到的正则表达式是 '^[a-zA-Z][a-zA-z ._-]'。

How can i use this regular expression on the string variable? Please help me.

我如何在字符串变量上使用这个正则表达式?请帮我。

Any other suggesstion is also welcome. Basically i need to have only alpha-numeric, dot,space, hyphen, underscore in the string value.

也欢迎任何其他建议。基本上我只需要在字符串值中包含字母数字、点、空格、连字符、下划线。

Please help.

请帮忙。

Part of answer:i am able to partly achieve the behavior using

部分答案:我能够部分实现使用

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

But i could not add dot, space, hyphen, underscore to the above validation. The above validation removes all the characters expect alpha-numeric characters. But i need dot, space, hyphen, underscore are also not to be replaced/removed from the orginal String.

但我无法在上述验证中添加点、空格、连字符、下划线。上述验证删除了除字母数字字符之外的所有字符。但我需要点、空格、连字符、下划线也不能从原始字符串中替换/删除。

Any ideas please??

请问有什么想法吗??

回答by Muhammad Imran Tariq

Just use .replaceAll("[aeiou]","")This will work.

只需使用.replaceAll("[aeiou]","")这将工作。

回答by Varun Vishnoi

Just use yourstring.split()method and split the string from where you want to remove the symbol and then again append the string.

只需使用yourstring.split()方法并从要删除符号的位置拆分字符串,然后再次附加字符串。

Have fun...

玩得开心...

回答by pajaja

Modify the regexp you have [^a-zA-Z0-9]to match those characters you want:

修改你必须[^a-zA-Z0-9]匹配那些你想要的字符的正则表达式:

string.replaceAll("[^a-zA-Z0-9\s\._-]", "");

回答by Varun Vishnoi

Yes you can easily do it by storing that string in any variable after that use StringBuilder object and append the character or symbol you want to add according to their place.

是的,您可以通过在使用 StringBuilder 对象之后将该字符串存储在任何变量中并根据它们的位置附加要添加的字符或符号来轻松实现。

yourString.setText(new StringBuilder().append("character or symbol").append(anystring)
                .append(":"));

You can easily do from above code.

您可以轻松地从上面的代码中完成。

回答by abed rayyan

String x = "a c d" you want to replace all the spaces by (-) x = x.replace(" ", "-");

String x = "ac d" 你想用 (-) x = x.replace(" ", "-") 替换所有的空格;