java 使用带有小数的 string.split() - 不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13460595/
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
Using string.split() with a decimal - not working
提问by CodyBugstein
I'm trying to split a line of text into multiple parts. Each element of the text is separated by a period. I'm using string.split("."); to split the text into an array of Strings, but not getting anywhere.
我正在尝试将一行文本分成多个部分。文本的每个元素都由句点分隔。我正在使用 string.split("."); 将文本拆分为一个字符串数组,但没有得到任何地方。
Here is a sample of the code:
下面是代码示例:
String fileName = "testing.one.two";
String[] fileNameSplit = fileName.split(".");
System.out.println(fileNameSplit[0]);
The funny thing is, when I try ":" instead of ".", it works? How can I get it to work for a period?
有趣的是,当我尝试使用 ":" 而不是 "." 时,它有效吗?我怎样才能让它工作一段时间?
回答by Asaph
String.split()
accepts a regular expression(regex for short) and dot is a special char in regexes. It means "match all chars except newlines". So you must escape it with a leading backslash. But the leading backslash is a special character in java string literals. It denotes an escape sequence. So it must be escaped too, with another leading backslash. Like this:
String.split()
接受正则表达式(简称 regex),点是正则表达式中的特殊字符。这意味着“匹配除换行符之外的所有字符”。所以你必须用一个前导反斜杠来逃避它。但是前导反斜杠是 java 字符串文字中的一个特殊字符。它表示一个转义序列。所以它也必须被转义,并使用另一个前导反斜杠。像这样:
fileName.split("\.");
回答by Juvanis
Try this one: fileName.split("\\.");
试试这个: fileName.split("\\.");
回答by kosa
fileName.split(".");
should be
应该
fileName.split("\.");
.is special character and split()accepts regex. So, you need to escape the special characters.
. 是特殊字符并且split()接受正则表达式。因此,您需要转义特殊字符。
A character preceded by a backslash
(\)
is an escape sequence and has special meaning to the compiler. Please read this documentation.
反斜杠前面的字符
(\)
是转义序列,对编译器具有特殊意义。请阅读本文档。
回答by paxdiablo
It's because the argument to split
is a regular expression, and .
means basically any character. Use "\\."
instead of "."
and it should work fine.
这是因为参数 tosplit
是一个正则表达式,.
基本上意味着任何字符。使用"\\."
而不是"."
它应该可以正常工作。
The regular expression for a literal period (as opposed to the any-character .
) is \.
(using the \
escape character forces the literal interpretation).
文字句点(与 any-character 相对)的正则表达式.
是\.
(使用\
转义字符强制文字解释)。
And, because it's within a string where \
already has special meaning, you need to escape thatas well.
而且,因为它是其中一个字符串中\
已经具有特殊的意义,你需要逃避那为好。
回答by ChuyAMS
You need to escape the "." character because split accept regular expressions and the . means any character, so for saying to the split method to split by point you must escape it like this:
你需要转义“。” 字符,因为 split 接受正则表达式和 . 表示任何字符,因此要对 split 方法说按点拆分,您必须像这样转义它:
String[] array = string.split('\.');