码迷,mamicode.com
首页 > 编程语言 > 详细

Brief introduction to Java String Split 【简单介绍下Java String Split】

时间:2017-05-08 23:19:36      阅读:204      评论:0      收藏:0      [点我收藏+]

标签: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】

标签:normal   dig   tac   int   arrays   character   better   mon   简单   

原文地址:http://www.cnblogs.com/evanstudy/p/6827838.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!