在Windows中,“ \ r \ n”用作行分隔符。正则表达式“ \\ r?\\ n”与行尾匹配。
split()String类的方法接受一个表示正则表达式的值,并将当前字符串拆分为标记(单词)数组,将两次匹配之间的字符串视为一个标记。
因此,如果要分割以行尾作为定界符split()的字符串,请通过传递上面指定的正则表达式作为参数在输入字符串上调用该方法。
示例import java.util.Scanner;
public class RegexExample {
public static void main(String[] args) {
System.out.println("输入您的输入字符串: ");
Scanner sc = new Scanner(System.in);
String input = " sample text \r\n line1 \r\n line2 \r\n line3 \r\n line4";
String[] strArray = input.split("\\r?\\n");
for (int i=0; i
System.out.println(strArray[i]);
}
}
}
输出结果输入您的输入字符串:
sample text
line1
line2
line3
line4