用于从字符串中删除不需要的字符的正则表达式

Regular expression to remove unwanted characters from the String

我有一个要求,需要删除 java 中不需要的字符串字符。 例如, 输入字符串是

Income ......................4,456
liability........................56,445.99

我希望输出为

Income 4,456
liability 56,445.99

在 java 中编写此内容的最佳方法是什么。我正在解析大型文档 为此,它应该进行性能优化。

最好的方法是:

String result = yourString.replaceAll("[-+.^:,]","");

这将用任何东西替换这个特殊字符。

对于这个特定的示例,我可能会使用以下替换:

String input = "Income ......................4,456";
input = input.replaceAll("(\w+)\s*\.+(.*)", " ");
System.out.println(input);

这里是对正在使用的模式的解释:

(\w+)   match AND capture one or more word characters
\s*     match zero or more whitespace characters
\.+     match one or more literal dots
(.*)     match AND capture the rest of the line

括号中的两个量称为捕获组。正则表达式引擎在匹配时记住它们是什么,并按顺序使它们可用,如 </code> 和 <code> 以在替换字符串中使用。

输出:

Income 4,456

Demo

您可以用这行代码替换:

System.out.println("asdfadf ..........34,4234.34".replaceAll("[ ]*\.{2,}"," "));