简体   繁体   English

String.split()之后的ArrayIndexOutOfBoundsException

[英]ArrayIndexOutOfBoundsException after String.split()

I got a string value from server: 我从服务器得到一个字符串值:

String fileName = requestServer();

//My log shows fileName="properties.txt"

String name = fileName.trim().split(".")[0];

But when I try to get the name without ".txt" with above code, I got 但是,当我尝试使用上面的代码获取不带“ .txt”的名称时,我得到了

ArrayIndexOutOfBoundsException: length=0, index=0.

I don't see where my code is wrong, why I get this exception? 我看不到我的代码在哪里错误,为什么会出现此异常?

This: String name = fileName.trim().split(".")[0]; 这: String name = fileName.trim().split(".")[0]; should be like so: String name = fileName.trim().split("\\\\.")[0]; 应该类似于: String name = fileName.trim().split("\\\\.")[0]; . The . . in regex language means any character (since String.split() takes a regular expression as a parameter.), which causes the string to be split on each character thus returning an empty array. 在正则表达式语言中,意味着任何字符 (因为String.split()使用regular expression作为参数。),这会导致字符串在每个字符上分割,从而返回一个空数组。

The \\ infront of . \\ infront . will escape the period and cause the regex engine to treat it like an actual . 跳过句点并使正则表达式引擎像实际那样对待它. character. 字符。 The extra \\ is needed so that the initial \\ can be escaped. 需要额外的\\以便可以将初始\\进行转义。

Use this 用这个

String name = fileName.trim().split("\\.")[0];

Explanation of the regex \\. 正则表达式\\的说明。

. is a regex metacharacter to match anything (except newline). 是一个正则表达式元字符,可以匹配任何内容(换行符除外)。 Since we want to match a literal . 既然我们要匹配一个文字。 we escape it with . 我们用来逃避它。 Since both Java Strings and regex engine use \\ as escape character we need to use \\\\ . 由于Java String和regex引擎都使用\\作为转义字符,因此我们需要使用\\\\

split(...) returns an empty array, because it takes a regex as argument. split(...)返回一个空数组,因为它使用一个正则表达式作为参数。 "." is for every word character. 适用于每个单词字符。 The characters, that are found by that regex aren't included in the result. 该正则表达式找到的字符不包含在结果中。

Use "\\\\." 使用"\\\\." instead to split. 而不是分裂。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM