如何在用特殊符号拆分字符串并将特殊符号包含到第一个子字符串后,从字符串中获取子字符串



我想将带有分号的字符串拆分为字符串数组,但无论何时使用分号拆分字符串,我都需要将该分号添加到第一个拆分字符串中。它正在添加到下一个拆分屏幕。

String sampleContent="hello ; hai ;  come fast ;";
            String SQLScripts[] = sampleContent.split("(?=\;)",-1);
            System.out.println(" SQLSCript Length is:"+SQLScripts.length);
            for(int m=0;m<SQLScripts.length;m++){
                System.out.println("After SQLScripts spliting with semi colon is : "+SQLScripts[m]);
            }`

我期望的输出是:

 SQLSCript Length is:4
After SQLScripts spliting with semi colon is : hello ;
After SQLScripts spliting with semi colon is : hai ;
After SQLScripts spliting with semi colon is : come fast ;

我得到的输出是:

 SQLSCript Length is:4
After SQLScripts spliting with semi colon is : hello 
After SQLScripts spliting with semi colon is : ; hai 
After SQLScripts spliting with semi colon is : ;  come fast 
After SQLScripts spliting with semi colon is : ;

尝试使用此正则表达式"(?<=;)",-1,可以包含;:

  public static void main(String[] args) {
    String sampleContent = "hello ; hai ; come fast ;";
    String SQLScripts[] = sampleContent.split("(?<=;)",-1);
    System.out.println("SQLSCript Length is:"+SQLScripts.length);
    for(int m=0;m<SQLScripts.length-1;m++){
        System.out.println("After SQLScripts spliting with semi colon is : "+SQLScripts[m]);
    }
  }

输出:

  SQLSCript Length is:4
  After SQLScripts spliting with semi colon is : hello ;
  After SQLScripts spliting with semi colon is :  hai ;
  After SQLScripts spliting with semi colon is :  come fast ;

您可以使用这个基于查找的正则表达式:

String sampleContent="hello ; hai ;  come fast ;";
String SQLScripts[] = sampleContent.split("(?<=;)\s+");
System.out.println(" SQLSCript Length is:"+SQLScripts.length);
for(int i=0;i<SQLScripts.length;i++){
    System.out.println("After SQLScripts spliting with semi colon is : "+SQLScripts[i]);
}

输出:

 SQLSCript Length is:3
After SQLScripts spliting with semi colon is : hello ;
After SQLScripts spliting with semi colon is : hai ;
After SQLScripts spliting with semi colon is : come fast ;

最新更新