gpt4 book ai didi

java - 需要正则表达式来删除多个换行符之间的空格

转载 作者:行者123 更新时间:2023-12-02 08:42:41 25 4
gpt4 key购买 nike

我正在处理一些 rawString,其中我需要从某些地方删除\n,而有些地方如果显示\n,我需要进入下一行。例如输入:-

 ** As the coronavirus impact weighs, LMT to advance more\nthan $50 mln to small, medium-sized business partners in its\nsupply chain to protect jobs, support economy \n  \n  *New line should start\n\nregular \n  \n \n  \n text.

I am getting the result Partially using this code

 String str = input.replaceAll("\\n","~").replaceAll("~\\s+",System.lineSeparator()+System.lineSeparator()).replaceAll("~", " ");

现在我得到的结果:

** As the coronavirus impact weighs, LMT to advance more than $50 mln to small, medium-sized business partners in its supply chain to protect jobs, support economy*New line should startregular text.

但问题是我连续得到不止一次“\n”,所有\n都替换为一个“\n”,因为此时我得到的“\n”带有空格,它会转到下一个行,例如,因此它就像“\n\n 关键字”,在这种情况下,“关键字”显示在正确的下一行中,但在该行上方创建一个额外的行会出现问题。任何人都可以帮忙解决这个问题吗?

预期:-

** As the coronavirus impact weighs, LMT to advance more than $50 mln to small, medium-sized business partners in its supply chain to protect jobs, support economy*New line should startregular text.

换行输入模式

\n\n\n SomeText\n\n SomeText\n\n\n\n SomeText

在上述所有模式中,someText 将从下一行开始。

图案只会创造空间

\nSomeText\n\n\nSomeText\n\n\nSomeText

在所有这些情况下都只会创建空间 "",

最佳答案

我建议进行以下更新:

String str = input
.replaceAll("(\\n\\s+){2,}","~") // find duplicate linefeeds with optional spaces
.replaceAll("\\n"," ") // replace remaining linefeeds with spaces
.replaceAll("\\s{3,}", "") // remove redundant spaces
.replaceAll("\\s{2}", " ") // replace duplicate spaces with one
.replaceAll("~", System.lineSeparator() + System.lineSeparator() // restore linefeeds
);

它产生以下文本:

** As the coronavirus impact weighs, LMT to advance more than $50 mln to small, medium-sized business partners in its supply chain to protect jobs, support economy 

*New line should start regular

text.

新测试用例更新

String str = input
.replaceAll("(\\n +\\n| \\n+ )","~") // mark duplicate linefeeds with optional spaces
.replaceAll("\\n+"," ") // replace remaining linefeeds with spaces
.replaceAll("(~\\s*)+","~") // remove duplicate linefeed marks with optional spaces
.replaceAll("\\s{3,}", "") // remove redundant spaces
.replaceAll("\\s{2}", " ") // replace duplicate spaces
.replaceAll("~", System.lineSeparator() + System.lineSeparator()) // restore linefeeds
;
System.out.println("[" + str + "]");

情况 2:“\n\n\n SomeText1、\n\n SomeText2\n、\n\n\n SomeText3”

[\n
\n
SomeText1,\n
\n
SomeText2 ,\n
\n
SomeText3]

情况 3:“\nSomeText1、\n\n\nSomeText2\n\n、\nSomeText3”

[ SomeText1, SomeText2 , SomeText3]

关于java - 需要正则表达式来删除多个换行符之间的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61275602/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com