可以使用String.split()方法在正则表达式的特定匹配项周围拆分指定的字符串。此方法有一个参数,即regex,它返回通过将输入字符串围绕regex的特定匹配项进行拆分而获得的字符串数组。
给出了一个演示如何拆分字符串的程序,如下所示:
public class Demo {
public static void main(String args[]) {
String regex = "_";
String strInput = "The_sky_is_blue";
System.out.println("Regex: " + regex);
System.out.println("Input string: " + strInput);
String[] strArr = strInput.split(regex);
System.out.println("\nThe split input string is:");
for (String s : strArr) {
System.out.println(s);
}
}
}输出结果
Regex: _ Input string: The_sky_is_blue The split input string is: The sky is blue
现在让我们了解上面的程序。
正则表达式和输入字符串被打印出来。然后,使用String.split()方法将输入字符串拆分为正则表达式值。然后打印分割输入。演示此代码段如下:
String regex = "_";
String strInput = "The_sky_is_blue";
System.out.println("Regex: " + regex);
System.out.println("Input string: " + strInput);
String[] strArr = strInput.split(regex);
System.out.println("\nThe split input string is:");
for (String s : strArr) {
System.out.println(s);
}