Java字符串拆分为“。” (点) [英] Java string split with "." (dot)

查看:126
本文介绍了Java字符串拆分为“。” (点)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么Java中此代码的第二行抛出 ArrayIndexOutOfBoundsException

Why second line of this code in Java throws ArrayIndexOutOfBoundsException?

String filename = "D:/some folder/001.docx";
String extensionRemoved = filename.split(".")[0];

虽然下面有效:

String driveLetter = filename.split("/")[0];

我使用的是Java 7.

I use Java 7.

推荐答案

如果要拆分文字点,则需要转义点:

You need to escape the dot if you want to split on a literal dot:

String extensionRemoved = filename.split("\\.")[0];

否则你正在拆分正则表达式 ,这意味着任何字符。

注意在正则表达式中创建单个反斜杠所需的双反斜杠。

Otherwise you are splitting on the regex ., which means "any character".
Note the double backslash needed to create a single backslash in the regex.

你得到一个 ArrayIndexOutOfBoundsException ,因为你的输入字符串只是一个点,即 ,这是一个边缘情况,在点上分割时产生一个空数组; split(正则表达式) ) 从结果中删除所有尾随空白,但由于在点上分割一个点只留下两个空格,在删除尾随空格后,你将留下一个空数组。

You're getting an ArrayIndexOutOfBoundsException because your input string is just a dot, ie ".", which is an edge case that produces an empty array when split on dot; split(regex) removes all trailing blanks from the result, but since splitting a dot on a dot leaves only two blanks, after trailing blanks are removed you're left with an empty array.

为避免获得此边缘情况的 ArrayIndexOutOfBoundsException ,请使用 split(正则表达式,限制) ,其第二个参数是结果数组的大小限制。当 limit 否定时,将禁用从结果数组中删除尾随空白的行为:

To avoid getting an ArrayIndexOutOfBoundsException for this edge case, use the overloaded version of split(regex, limit), which has a second parameter that is the size limit for the resulting array. When limit is negative, the behaviour of removing trailing blanks from the resulting array is disabled:

".".split("\\.", -1) // returns an array of two blanks, ie ["", ""]

即,当文件名只是一个点,调用 filename.split(\\。, - 1)[0] 将返回空白,但调用 filename.split(\\。)[0] 将抛出 ArrayIndexOutOfBoundsException

ie, when filename is just a dot ".", calling filename.split("\\.", -1)[0] will return a blank, but calling filename.split("\\.")[0] will throw an ArrayIndexOutOfBoundsException.

这篇关于Java字符串拆分为“。” (点)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆