开发者

Error when using Java String split

开发者 https://www.devze.com 2022-12-25 21:05 出处:网络
HI All, I\'ve been using the basic split for a while - where I just parse out a string into an array based on a simple token like \" \" or \",\".

HI All,

I've been using the basic split for a while - where I just parse out a string into an array based on a simple token like " " or ",".

So of开发者_开发知识库 course a customer tries this: \\.br\ which fails miserably.

I need to parse to an array of lines. The string for example looks like this:

"LINE 1\\.br\\LINE 2\\.br\\LINE 3\\.br\\LINE 4\\.br\\"

and this fails with java.util.regex.PatternSyntaxException: Unexpected internal error.

Any ideas?


You can use Pattern.quote() to escape a string for using as regexp:

... = s.split(Pattern.quote("\\.br\\"));


Don't forget String.split takes a Regex, and most people put in a string literal, so you have to escape the \ for regex and escape it for strings, so you end up with "\\\" in your String argument to represent a single \ character.

e.g.

String.split("\\\")

so in your case:

String.split("\\\\\\.br\\\\") // extra slash for regex, and String encoded
0

精彩评论

暂无评论...
验证码 换一张
取 消