基本上,我想知道是否有一个方便的类或方法来过滤不需要的字符的字符串。该方法的输出应该是“清理过的”字符串。即:
String dirtyString = "This contains spaces which are not allowed"
String result = cleaner.getCleanedString(dirtyString);
预期结果是:
"Thiscontainsspaceswhicharenotallowed"
一个更好的例子:
String reallyDirty = " this*is#a*&very_dirty&String"
String result = cleaner.getCleanedString(dirtyString);
我希望结果是:
"thisisaverydirtyString"
因为,我让清洁工知道 ' '、'*'、'#'、'&' 和 '_' 是脏字符。我可以通过使用白/黑列表字符数组来解决它。但我不想重新发明轮子。
我想知道是否已经存在可以使用正则表达式“清理”字符串的东西。而不是自己写这个。
补充: 如果您认为清理字符串可以做得不同/更好,那么我当然也会全神贯注
另一个补充: - 它不仅适用于空格,还适用于任何类型的字符。
最佳答案
根据您的更新编辑:
dirtyString.replaceAll("[^a-zA-Z0-9]","")
关于java - 如何使用正则表达式过滤不需要的字符的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4945695/