我需要在java中删除字符串中不需要的字符。例如,输入字符串是
Income ......................4,456
liability........................56,445.99我想要输出
Income 4,456
liability 56,445.99用java编写这篇文章的最佳方法是什么?为此,我正在解析大型文档,因此应该对其性能进行优化。
发布于 2017-06-13 02:30:12
您可以使用以下代码行替换此代码:
System.out.println("asdfadf ..........34,4234.34".replaceAll("[ ]*\\.{2,}"," "));发布于 2017-06-13 02:26:08
对于这个特定的例子,我可以使用以下替换:
String input = "Income ......................4,456";
input = input.replaceAll("(\\w+)\\s*\\.+(.*)", "$1 $2");
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括号中的两个量称为捕获组。regex引擎在匹配时会记住它们是什么,并按顺序将它们作为$1和$2在替换字符串中使用。
输出:
Income 4,456
Demo
发布于 2017-06-13 02:25:51
最好的方法是:
String result = yourString.replaceAll("[-+.^:,]","");这将取代这个特殊的角色。
https://stackoverflow.com/questions/44511393
复制相似问题