2016-08-19 80 views
0

我想用[,.!?;~]分割字符串,但我想留在[,.!?;~]其位置,例如:如何編寫正則表達式來以這種格式分割字符串?

這就是例子,但它是不夠的

[This is the example,, but it is not enough] // length=2 
[0]=This is the example, 
[1]=but it is not enough 

正如你所看到的,逗號仍然存在。我用這個正則表達式(?<=([,.!?;~])+)我想如果一些特殊的單詞(例如:但是)在[,.!?;~]之後,那麼不要拆分那部分字符串。例如:

我想把這句話分成這種形式,但怎麼辦。所以,如果 任何人都可以幫助,那將是巨大的

[0]=I want this sentence to be split into this form, but how to do. 
[1]=So if anyone can help, 
[2]=that will be great 

正如你可以看到這部分(形式,但)沒有分裂INT的第一句話。

+3

使用負前瞻。 '(?<= [,。!?;〜])(?!但)'。 –

回答

2

我用:

  1. 正回顧後(?<=a)b保持分隔符。
  2. Negative Lookahead a(?!b)排除停用詞。

請注意我是如何在您提供RegEx後添加RegEx (?!\\s*(but|and|if))的。您可以將所有必須排除的停用詞(例如,但是,如果)放在由pipe symbol分隔的括號內。

另外請注意,分隔符仍然在它的位置。

輸出

Count of tokens = 3 
I want this sentence to be split into this form, but how to do. 
So if anyone can help, 
that will be great 

代碼

import java.lang.*; 

public class HelloWorld { 
    public static void main(String[] args) { 
     String str = "I want this sentence to be split into this form, but how to do. So if anyone can help, that will be great"; 
     //String delimiters = "\\s+|,\\s*|\\.\\s*"; 
     String delimiters = "(?<=,)"; 

     // analyzing the string 
     String[] tokensVal = str.split("(?<=([,.!?;~])+)(?!\\s*(but|and|if))"); 

     // prints the number of tokens 
     System.out.println("Count of tokens = " + tokensVal.length); 

     for (String token: tokensVal) { 
      System.out.println(token); 
     } 
    } 
} 
+1

謝謝先生!這就是想要的。 –

相關問題