Brief introduction to Java String Split 【簡單介紹下Java String Split】

來源:互聯網
上載者:User

標籤:normal   dig   tac   int   arrays   character   better   mon   簡單   

Split is a common function in Java. It split a full string to an array based on delimeter.

For example, split "a:b:c" with ":" results in [a, b, c]

In some scenario, it‘s better to keep the delimeter instead of discard it while splitting.

Here are some strategies.

分割(split) 是java裡一個常用的函數,它根據分隔字元將完整的字串切分成數組

比如 "a:b:c"通過":"切分會得到數組[a, b, c]

然而某些情境下,可能我們想要保留分隔字元

這裡是一些保留分隔字元的方法

System.out.println(Arrays.toString("a:b:c".split(":")));  //normal split
//[a, b, c]
System.out.println(Arrays.toString("a:b:c".split("(?=:)"))); //look behind
//[a, :b, :c]
System.out.println(Arrays.toString("a::b:c".split("(?=:)"))); //look behind
//[a, :, :b, :c]
System.out.println(Arrays.toString("a:b:c".split("(?<=:)"))); //look ahead
//[a:, b:, c]
System.out.println(Arrays.toString("a:b:c".split("(?!:)"))); //look ahead
//[a:, b:, c]
System.out.println(Arrays.toString("a:b:::c".split("(?!=:)"))); //look bothway
//[a, :, b, :, :, :, c]
System.out.println(Arrays.toString("a:b:::c".split("(?<=:)|(?=:)"))); //look bothway
//[a, :, b, :, :, :, c]

 

Look ahead  前向結合

delimeter will be attached to the previous string

分隔字元會附加在前向字串後面

Look behind  後向結合

delimeter will be attached to the subsequent string

分隔字元會附加在後向字串前面

Look bothway  完全分離

similar to normal split, but every delimeter will be included in the array

和普通分割很像,但每個分隔字元也會出現在數組中

 

Some interesting usage

一些有趣的用法

System.out.println(Arrays.toString("1a2bb3ccc".split("(?<=[a-z])(?=[0-9])")));  //digit + [a-z]characters
//[1a, 2bb, 3ccc]
System.out.println(Arrays.toString("1_1112_222aditional3_333".split("(?<=_..)"))); //"_" with 2 more chars
//[1_11, 12_22, 2aditional3_33, 3]
System.out.println(Arrays.toString("1_1112_222aditional3_3333".split("(?<=_.{3})"))); //"_" with 3 more chars
//[1_111, 2_222, aditional3_333, 3]
System.out.println(Arrays.toString("1_1112_222aditional3_33".split("(?<=_.{3})"))); //"_" with 3 more chars
//[1_111, 2_222, aditional3_33]

 

Brief introduction to Java String Split 【簡單介紹下Java String Split】

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.