简体   繁体   English

用Java拆分字符串不起作用

[英]Splitting a string with java not working

I have a string in java that looks something like: 我在java中有一个字符串,看起来像:

holdingco^(218) 333-4444^scott@holdingco.com

I set a string variable equal to it: 我设置了一个等于它的字符串变量:

String value = "holdingco^(218) 333-4444^scott@holdingco.com";

Then I want to split this string into it's components: 然后,我想将此字符串拆分为它的组件:

String[] components = value.split("^");

However it does not split up the string. 但是,它不会拆分字符串。 I have tried escaping the carrot delimiter to no avail. 我试图将胡萝卜定界符转义无济于事。

Use 采用

String[] components = value.split("\\^");

The unescaped ^ means beginning of a string in a regex, and the unescaped $ means end. 未转义的^表示正则表达式中字符串的开头,未转义的$表示结尾。 You have to use two backslashes for escaping, as the string literal "\\\\" represents a single backslash, and that's what regex needs. 您必须使用两个反斜杠进行转义,因为字符串文字"\\\\"代表一个反斜杠,这正是regex所需要的。

If you tried escaping with one backslash, it didn't compile, as \\^ is not a valid escape sequence in Java. 如果您尝试使用一个反斜杠转义,则它不会编译,因为\\^在Java中不是有效的转义序列。

try with: value.split("\\\\^"); 尝试: value.split("\\\\^"); this should work a bit better 这应该更好一些

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM