java 正则表达式 split,提供正则表达式时,Java中的String.split()方法到底如何工作?...

小编典典

它"\\S"在正则表达式引擎中表示\S非空白字符的每个字符上进行拆分。

因此,让我们尝试分割"x

x"非空白(\S)。由于此正则表达式可以用一个字符进行匹配,因此可以对其进行迭代以标记拆分的位置(我们将使用竖线|进行表示)。

是'x'一个非空白?是的,让我们标记一下| x

是' '一个非空白?不,所以我们保持原样

是最后一个'x'非空白吗?是的,让我们标记一下| |

因此,作为结果,我们需要在开始和结束时拆分字符串,这最初会给我们结果数组

["", " ", ""]

^ ^ - here we split

但是由于删除了结尾的 空字符串 ,结果将是

[""," "]

,""]

因此split返回["", " "]仅包含两个元素的数组。

顺便说一句。要关闭删除最后一个空字符串的操作,您需要使用split(regex,limit)limit的负值,例如split("\\S",-1)。

现在回到您的示例。如果您有数据,则将每个

I am preparing for OCPJP

| || ||||||||| ||| |||||

意思是

""|" "|""|" "|""|""|""|""|""|""|""|""|" "|""|""|" "|""|""|""|""|""

所以这代表这个数组

[""," ",""," ","","","","","","","",""," ","",""," ","","","","",""]

但是由于""删除了结尾的空字符串(如果它们的存在是由split引起的-

有关更多信息,请访问:混淆String.split的输出)

[""," ",""," ","","","","","","","",""," ","",""," ","","","","",""]

^^ ^^ ^^ ^^ ^^

您得到的结果数组仅包含以下部分:

[""," ",""," ","","","","","","","",""," ","",""," "]

正好是16个元素

2020-09-15

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值