How to use String#split with a backslash character?

匿名 (未验证) 提交于 2019-12-03 08:57:35

问题:

I would like to split this string:

 C:\RCOUNT2013\2013_Extracted\Weekly ODEN Notices Report.12-28-2013.2013-12-29 07-20-51.pdf.log.0 

on the \. What would the regex be?

string.split("\\ \")  // ? 

回答1:

In regex-land, a \ is an escape character, so to obtain a literal \ we need to escape it: \\. However, in Java strings, \ is also an escape character, so we need to escape each \ a second time, resulting in \\\\. Therefore, this is what you want:

str.split("\\\\") 


回答2:

split("\\\\") 

Double-escaping "\"



回答3:

The regex would be "\\\\"

In the source code: "\\\\"

After compiling, the string is: "\\"

And the regex parser interperets this as look for a \, So it matches one backslash '\'



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!