Java正则表达式value.split("\\."),"反斜杠点"除以字符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1480284/
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
Java regular expression value.split("\\."), "the back slash dot" divides by character?
提问by Nap
From what I understand, the backslash dot (\.
) means one character of any character? So because backslash is an escape, it should be backslash backslash dot ("\\."
)
据我了解,反斜杠点 ( \.
) 表示任何字符中的一个字符?所以因为反斜杠是转义符,所以应该是反斜杠反斜杠点("\\."
)
What does this do to a string? I just saw this in an existing code I am working on. From what I understand, it will split the string into individual characters. Why do this instead of String.toCharArray()
. So this splits the string to an array of string which contains only one char for each string in the array?
这对字符串有什么作用?我刚刚在我正在处理的现有代码中看到了这一点。据我了解,它会将字符串拆分为单个字符。为什么要这样做而不是String.toCharArray()
. 所以这将字符串拆分为一个字符串数组,该数组中的每个字符串只包含一个字符?
采纳答案by Stephen C
My guess is that you are missing that backslash ('\') characters are escape characters in Java String literals. So when you want to use a '\' escape in a regex written as a Java String you need to escape it; e.g.
我的猜测是您缺少反斜杠 ('\') 字符是 Java 字符串文字中的转义字符。因此,当您想在编写为 Java 字符串的正则表达式中使用 '\' 转义符时,您需要对其进行转义;例如
Pattern.compile("\."); // Java syntax error
// A regex that matches a (any) character
Pattern.compile(".");
// A regex that matches a literal '.' character
Pattern.compile("\.");
// A regex that matches a literal '\' followed by one character
Pattern.compile("\\.");
The String.split(String separatorRegex)
method splits a String into substrings separated by substrings matching the regex. So str.split("\\.")
will split str
into substrings separated by a single literal '.' character.
该String.split(String separatorRegex)
方法将字符串拆分为由匹配正则表达式的子字符串分隔的子字符串。因此str.split("\\.")
将拆分str
为由单个文字 '.' 分隔的子字符串。特点。
回答by nall
The regex "." would match any character as you state. However an escaped dot "\." would match literal dot characters. Thus 192.168.1.1 split on "\." would result in {"192", "168", "1", "1"}.
正则表达式“.” 将匹配您所说的任何字符。但是转义点“\”。将匹配文字点字符。因此 192.168.1.1 在“\”上分裂。将导致 {"192", "168", "1", "1"}。
Your wording isn't completely clear, but I think this is what you're asking.
你的措辞并不完全清楚,但我认为这就是你要问的。