[英]Splitting a string on whitespaces
我正在尝试将字符串拼接成多行字符串。 正则表达式应该选择之前有13个字符的空格。
问题是13个字符计数在前一个选定的空格后没有重置。 因此,在前13个字符之后,正则表达式选择每个空格。
我正在使用以下正则表达式,其中包含13个字符的positive look-behind
:
(?<=.{13})
(最后有一个空格)
你可以在这里测试正则表达式和以下代码:
import java.util.ArrayList;
public class HelloWorld{
public static void main(String []args){
String str = "This is a test. The app should break this string in substring on whitespaces after 13 characters";
for (String string : str.split("(?<=.{13}) ")) {
System.out.println(string);
}
}
}
此代码的输出如下:
这是一个测试。
该
应用
应该
打破
这个
串
在
子
上
空格
后
13
人物
但它应该是:
这是一个测试。
该应用程序应该
打破这个字符串
在substring上
之后的空白
13个字符
您实际上可能使用惰性限制量词来匹配行,然后用$0\\n
替换:
.{13,}?[ ]
请参阅正则表达式演示
IDEONE演示 :
String str = "This is a test. The app should break this string in substring on whitespaces after 13 characters";
System.out.println(str.replaceAll(".{13,}?[ ]", "$0\n"));
请注意,模式匹配:
.{13,}?
- 任何不是换行符的字符(如果你需要匹配任何字符,使用DOTALL修饰符,虽然我怀疑你在当前场景中需要它),至少13次,它可以匹配更多的字符,但直到第一个空格遇到 [ ]
- 文字空间(字符类是多余的,但它有助于可视化模式)。 替换模式 - "$0\\n"
- 重新插入整个匹配值(它存储在组0中)并在其后附加换行符。
您可以在空格之前匹配并捕获13个字符,而不是分割。
Java代码:
Pattern p = Pattern.compile( "(.{13}) +" );
Matcher m = p.matcher( text );
List<String> matches = new ArrayList<>();
while(m.find()) {
matches.add(m.group(1));
}
它会产生:
This is a test.
The app should
break this string
in substring on
whitespaces after
13 characters
您可以使用.split并使用正则表达式执行此操作。 就像这样
line.split("\\s+");
这将使每个单词溢出一个或多个空格。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.