为什么.split(“\\”)生成异常? [英] Why does .split("\\") generate an exception?

查看:113
本文介绍了为什么.split(“\\”)生成异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表示目录的String,其中 \ 用于分隔文件夹。我想根据\\拆分:

I have a String representing a directory, where \ is used to separate folders. I want to split based on "\\":

String address = "C:\\saeed\\test";
String[] splited = address.split("\\");

然而,这给了我一个 java.util.regex.PatternSyntaxException

推荐答案

正如其他人所建议的那样,您可以使用:

As others have suggested, you could use:

String[] separated = address.split("\\\\");

或者你可以使用:

String[] separated = address.split(Pattern.quote("\\")); 

此外,仅供参考:

String address = "C:\saeed\test";

将无法编译,因为 \s 不是有效的转义序列。这里 \t 被解释为制表符,你真正想要的是:

will not compile, since \s is not a valid escape sequence. Here \t is interpreted as the tab character, what you actually want is:

String address = "C:\\saeed\\test";

所以,现在我们看到为了获得 \ 字符串中,我们需要\\


正则表达式 \\ 匹配单个反斜杠,因为 \ 是正则表达式中的特殊字符,因此必须逃脱。一旦我们把它放在引号中,又把它变成 String ,我们需要转义每个反斜杠,产生\\\ \

So, now we see that in order to get a \ in a String, we need "\\".

The regular expression \\ matches a single backslash since \ is a special character in regex, and hence must be escaped. Once we put this in quotes, aka turn it into a String, we need to escape each of the backslashes, yielding "\\\\".

这篇关于为什么.split(“\\”)生成异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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