gpt4 book ai didi

java - 按空格分割但不换行

转载 作者:行者123 更新时间:2023-12-01 17:22:19 24 4
gpt4 key购买 nike

我正在尝试使用以下代码将给定字符串中的所有链接转换为可点击的 a 标记:

String [] parts = comment.split("\\s");
String newComment=null;

for( String item : parts ) try {
URL url = new URL(item);
// If possible then replace with anchor...
if(newComment==null){
newComment="<a href=\"" + url + "\">"+ url + "</a> ";
}else{
newComment=newComment+"<a href=\"" + url + "\">"+ url + "</a> ";
}
} catch (MalformedURLException e) {
// If there was an URL that was not it!...
if(newComment==null){
newComment = item+" ";
}else{
newComment = newComment+item+" ";
}
}

它适用于

Hi there, click here http://www.google.com ok?

将其转换为

Hi there, click here <a href="http://www.google.com">http://www.google.com</a> ok?

但是当字符串是这样的时:

Hi there, click 

here http://www.google.com

ok?

它仍在将其转换为:

Hi there, click here <a href="http://www.google.com">http://www.google.com</a> ok?

而我希望最终结果是:

Hi there, click 

here <a href="http://www.google.com">http://www.google.com</a>

ok?

我认为它在进行分割时也包括换行符。

在这种情况下如何保留换行符?

最佳答案

我建议采用不同的方法:

String noNewLines = "Hi there, click here http://www.google.com ok?";
String newLines = "Hi there, \r\nclick here \nhttp://www.google.com ok?";
// This is a String format with two String variables.
// They will be replaced with the desired values once the "format" method is called.
String replacementFormat = "<a href=\"%s\">%s</a>";
// The first round brackets define a group with anything starting with
// "http(s)". The second round brackets delimit that group by a lookforward reference
// to whitespace.
String pattern = "(http(s)?://.+?)(?=\\s)";
noNewLines = noNewLines.replaceAll(
pattern,
// The "$1" literals are group back-references.
// In our instance, they reference the group enclosed between the first
// round brackets in the "pattern" String.
new Formatter().format(replacementFormat, "$1", "$1")
.toString()
);
System.out.println(noNewLines);
System.out.println();
newLines = newLines.replaceAll(
pattern,
new Formatter().format(replacementFormat, "$1", "$1")
.toString()
);
System.out.println(newLines);

输出:

Hi there, click here <a href="http://www.google.com">http://www.google.com</a> ok?

Hi there,
click here
<a href="http://www.google.com">http://www.google.com</a> ok?

这会将您的所有 http(s) 链接替换为 anchor 引用,无论您的文本中是否有换行符(windows 或 *nix)。

编辑

为了获得最佳编码实践,您应该将 replacementFormatpattern 变量设置为常量(例如,final static String REPLACement_FORMAT 等等)。

编辑二

实际上,对 URl 模式进行分组并不是真正必要的,因为空白前瞻就足够了。但好吧,我保持原样,它有效。

关于java - 按空格分割但不换行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17706873/

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