繁体   English   中英

java-regex 在 80 个字符后拆分字符串。 如果字符串中间分割到最近的空间之前

[英]java-regex split string after 80 char. if middle of string split to closest space before

我有一个长字符串,我想将我的字符串拆分为 80 个字符,但是如果我拆分字符串时它是一个单词的中间,那么我会采用最接近的前一个空格。

在我得到的下面:

String myStr = "very long string supposed to exceed eighty characters because some addresses are very long but they have space so should not be an issue to split them"
String[] splitString = myStr.split("[\\s\\S]{1,80}(?!\\S)");

log.info("split string : {}", splitString); => // return {}
  
//Expected result : 
splitString[0] => "very long string supposed to exceed eighty characters because some addresses are"

splitString[1] => " very long but they have space so should not be an issue to split them"

有人可以告诉我我错过了什么吗?

我确实在https://regex101.com/上测试了我的正则表达式,它按照我的意愿拆分了我的字符串。 我知道这个网站在 JS 中测试正则表达式,但我猜想正则表达式在每种语言中都非常相似。

谢谢你的帮助:)

可能很难表达一个足够聪明的正则表达式模式,一次只能在空格上拆分最多 80 个字符。 但是,如果我们使用正式的正则表达式模式匹配器,则相当简单:

String myStr = "very long string supposed to exceed eighty characters because some addresses are very long but they have space so should not be an issue to split them";
String pattern = ".{1,80}(?!\\S)";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(myStr);
while (m.find()) {
    System.out.println(m.group(0).trim() + " (length: " + m.group(0).trim().length() + ")");
}

这打印:

very long string supposed to exceed eighty characters because some addresses are (length: 80)
very long but they have space so should not be an issue to split them (length: 69)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM