如何从String中删除一些字符 [英] How do I remove some characters from my String

查看:148
本文介绍了如何从String中删除一些字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从我的字符串中删除所有以下字符

i want to remove all of the following chars from my string


> [], -

">[],-"

此刻我正在这样做。但必须有一个更有效的方式

at the moment im doing this. but there must be a more efficient way

newString = myString.replace(">","").replace("[","").replace("]","")....


推荐答案

使用描述所有要替换的字符的正则表达式,替换与正则表达式匹配的所有内容的方法:

Use a regex that describes all the characters you want to replace, with the method that replaces everything matching the regex:

newString = myString.replaceAll("[<>\\[\\],-]", "");

(编辑:我不认为<> 应该被转义。我忘了加倍反斜杠,因为它们将被解释两次:一次是Java编译器,一次是正则表达式引擎。)

(edited: I don't think <> are supposed to be escaped, actually. And I forgot to double up the backslashes since they'll be interpreted twice: once by the Java compiler, and again by the regular expression engine.)

这篇关于如何从String中删除一些字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆