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

时间:2015-12-16 07:04:26

标签: java regex string split

我想用分号将字符串拆分为字符串数组,但每当用分号拆分字符串时,我需要将该分号添加到第一个拆分字符串中。它正在添加到下一个分割屏幕。

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 : ;

2 个答案:

答案 0 :(得分:1)

您可以根据lookbehind使用此正则表达式:

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 ;

答案 1 :(得分:1)

尝试使用此正则表达式"(?<=;)",-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 ;