拆分Java字符串返回空数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18508195/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Splitting a Java String return empty array?
提问by Programmer
I have a String something like this
我有一个像这样的字符串
"myValue"."Folder"."FolderCentury";
I want to split from dot("."). I was trying with the below code:
我想从点(“。”)拆分。我正在尝试使用以下代码:
String a = column.replace("\"", "");
String columnArray[] = a.split(".");
But columnArray
is coming empty. What I am doing wrong here?
但columnArray
即将空虚。我在这里做错了什么?
I will want to add one more thing here someone its possible String array object will contain spitted value like mentioned below only two object rather than three.?
我想在这里再添加一件事,它可能的 String 数组对象将包含如下所述的吐出值,只有两个对象而不是三个。?
columnArray[0]= "myValue"."Folder";
columnArray[1]= "FolderCentury";
采纳答案by Maroun
Note that String#splittakes a regex.
请注意,String#split需要一个regex。
You need to escape the special char.
(That means "Any character"):
您需要转义特殊字符.
(这意味着“任何字符”):
String columnArray[] = a.split("\.");
(Escaping a regex is done by \
, but in Java, \
is written as \\
).
(转义正则表达式由 完成\
,但在 Java 中,\
写为\\
)。
You can also use Pattern#quote:
您还可以使用Pattern#quote:
Returns a literal pattern Stringfor the specified String.
返回指定字符串的文字模式字符串。
String columnArray[] = a.split(Pattern.quote("."));
String columnArray[] = a.split(Pattern.quote("."));
By escapingthe regex, you tell the compiler to treat the .
as the String.
and not the special char.
.
通过转义正则表达式,您告诉编译器将.
视为String.
而不是特殊的 char.
。
回答by Arnaud Denoyelle
You must escape the dot.
你必须逃避点。
String columnArray[] = a.split("\.");
回答by Aniket Thakur
split() accepts an regular expression. So you need to skip '.' to not consider it as a regex meta character.
split() 接受一个正则表达式。所以你需要跳过'.' 不要将其视为正则表达式元字符。
String[] columnArray = a.split("\.");
回答by Praveen P Moolekandathil
While using special characters need to use the particular escape sequence with it.
使用特殊字符时需要使用特定的转义序列。
'.' is a special character so need to use escape sequence before '.' like:
'.' 是一个特殊字符,因此需要在 '.' 之前使用转义序列。喜欢:
String columnArray[] = a.split("\.");
回答by Tomas Narros
The next code:
下一个代码:
String input = "myValue.Folder.FolderCentury";
String regex = "(?!(.+\.))\.";
String[] result=input.split(regex);
System.out.println(Arrays.toString(result));
Produces the required output:
产生所需的输出:
[myValue.Folder, FolderCentury]
The regular Expression tweaks a little with negative look-ahead (this (?!)
part), so it will only match the last dot on a String with more than one dot.
正则表达式对负前瞻(这一(?!)
部分)进行了一些调整,因此它只会匹配字符串上的最后一个点,并且超过一个点。