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

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

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

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

因此,让我们尝试分割

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

  • 'x'
    一个非空白?是的,让我们标记一下
    | x
  • ' '
    一个非空白?不,所以我们保持原样
  • 是最后一个
    'x'
    非空白吗?是的,让我们标记一下
    | |

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

["", " ", ""]   ^    ^ - here we split

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

[""," "]     <- result        ,""] <- removed trailing empty string

因此split返回

["", " "]
仅包含两个元素的数组。

顺便说一句。要关闭删除最后一个空字符串的 *** 作,您需要使用

split(regex,limit)
limit的负值,例如
split("\S",-1)


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

I am preparing for OCPJP| || ||||||||| ||| |||||

意思是

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

所以这代表这个数组

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

但是由于

""
删除了结尾的空字符串(如果它们的存在是由split引起的-
有关更多信息,请访问:混淆String.split的输出)

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

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

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

正好是16个元素



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5478268.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-12
下一篇 2022-12-12

发表评论

登录后才能评论

评论列表(0条)

保存