Java按照一定的规则编辑文本

标签 java

我必须按照一定的规则编辑文本:

同一个单词中的重复字母将被缩减为单个字母。

"Questions" instead of "QuestionssSsS"

单词之间的多个空格将减少为一个空格

"go to the cinema" instead of "go    to   the     cinema"

与单词分开的单个字母将连接到单词

"first ten person" instead of "firs t ten person"

例如:

String s = "I am enouuugGh of an artis t to draw         freely upon my imagination. ImaginatioOO n is more importan t than      knowledge. KKkKkKnowledge is limited. Imagination encircles the wwWorl d.";

预期输出:

I am enough of an artist to draw freely upon my imagination. Imagination is more important than knowledge. Knowledge is limited. Imagination encircles the world.

请大家提出建议和建议。

最佳答案

String s = "I am enouuugGh of an artis t to draw         freely upon my imagination. ImaginatioOO n is more importan t than      knowledge. KKkKkKnowledge is limited. Imagination encircles the wwWorl d.";
System.out.println(s);
System.out.println("========================================================");
s = s.replaceAll("\\s+"," ");
s = s.replaceAll("(?i)(\\w)\\1+","$1");
s = s.replaceAll("(\\w+) (\\w)(?=[ \\.\\?!,])","$1$2");
System.out.println(s);

输出:我是一名足够的艺术家,可以自由地发挥我的想象力。想象力比知识更重要。知识有限。想象力包围世界。

 ==> \\s+ Several whitespace characters
 ==> \\w means A word character, short for [a-zA-Z_0-9]
 ==> \\w+ will represent one or more characters of \\w class
 we will also place it in group (\\w+) - this will be 2nd group
 ==> Pattern.CASE_INSENSITIVE flag is (?i)
 ==> $number is backreferrence

关于Java按照一定的规则编辑文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18873860/

相关文章:

java - 在多个实例和单个数据库上的 Cloud Foundry Java 应用程序中提供数据一致性

java - 在 Android 设备上使用 javascript 检测方向

java - 如何使用servlet验证HTML表单中不存在的隐藏表单字段名称

java - 将反斜杠字符分配给java String

java - 如何使用 JTable 的行排序器恢复原始行顺序?

java - Spring Integration TCP 连接在多线程负载/压力测试下被拒绝

java - 如何制作用于搜索的文本字段(使用谷歌搜索等提示)

java - Swing:一列的多个 CellEditor

java - 通过 Intent 发送电子邮件而无需按发送按钮

java - 通过 Java 发送电子邮件 - javax.mail.MessagingException : Could not connect to SMTP host: localhost, port: 587;