2016-10-19 12 views
0

我有一個字符串。我想在不平坦的白色空間上分割字符串。如果白色空間的長度大於或等於2個空格,那麼我希望它們位於單獨的數組項中,但是如果只有一個空格,那麼我希望它們位於同一個數組項中,例如,分裂具有多於或等於兩個空格的字符串

我有這個字符串

1234 This is a Test      PASS   1255432    12/21/2016 07:14:11 

所以當我分裂上面的字符串,它應該是這樣的

arr(0) = 1234 
arr(1) = This is a test ' because it has only one space in between, it  there are more or equal to two spaces than I want it to be a seperate item in an array 
arr(2) = Pass 
arr(3) = 1255432 
arr(4) = 12/21/2016 
arr(5) = 07:14:1 

與下面的字符串同樣的事情:

0001 This is a Marketing text_for the students  TEST2    468899       12/23/2016 06:23:16 

當我拆分上面的字符串,它應該是這樣的:

arr(0)=0001 
arr(1) = This is a Marketing text_for the students 
arr(2) = Test2 
arr(3)=468899 
arr(4)=12/23/2016 
arr(5) = 06:23:16 

是否有任何正則表達式,可以幫助我拆基於空間的字符串,但放話說起來如果空間更多或等於2

任何幫助將不勝感激。

+1

用'@「\ s {2,}分割」'' –

+0

這樣大量的數組項目將爲空。我可以得到像我上面提到的 – Anjali5

+0

你甚至沒有嘗試過。 https://regex101.com/r/7aBvcg/1 –

回答

0

這可以用這個表達式來完成(\ S {0,1} \ S +)+像這樣:

  string text = "0001 This is a Marketing text_for the students  TEST2    468899       12/23/2016 06:23:16"; 
      Regex regex = new Regex(@"(\s{0,1}\S+)+"); 

      var matches = regex.Matches("0001 This is a Marketing text_for the students  TEST2    468899       12/23/2016 06:23:16").Cast<Match>() 
            .Select(m => m.Value) 
             .ToArray(); 

      Console.WriteLine(String.Join(",", matches)); 

這是同樣的事情可以使用的Java腳本代碼段。

var value = "0001 This is a Marketing text_for the students  TEST2    468899       12/23/2016 06:23:16"; 
 
var matches = value.match(
 
    new RegExp("(\\s{0,1}\\S+)+", "gi") 
 
); 
 
console.log(matches)

此正則表達式(\s{0,1}\S+)+通過在每個匹配的與\ S {0,1},然後任意數量的事情是不與\ S的空間乞匹配0或1位工作+它然後通過將其包含在圓括號中並使用+運算符(...)+將這個整個事物匹配任意次,這允許單個空格字符串在一起。