简体   繁体   English

Java String.split无法正常工作

[英]Java String.split not working

I have a string in following format: 我有以下格式的字符串:

CT-d0712728-867d-4cc4-bd0c-b2a679b8385f~#$~2012-10-16 02:13:27 PM

Can I use String.split("~#$~") or do I have to use StringTokenizer? 我可以使用String.split("~#$~")还是必须使用StringTokenizer? I will have ONLY 2 parameters in above string, that's why I was trying to use String.Split("~#$~") but it doesn't seem to work. 我在上面的字符串中只有2个参数,这就是为什么我尝试使用String.Split(“〜#$〜”)的原因,但是它似乎不起作用。

$ is special character in regex (it means "end of a line"). $是正则表达式中的特殊字符 (表示“行尾”)。 To make it simple literal you need to escape it, for example with 为了简化文字,您需要对其进行转义,例如

  • "\\\\$" , "\\\\$"
  • "[$]"
  • or using quotations "\\\\Q$\\\\E" . 或使用引号"\\\\Q$\\\\E"

Since split() method takes the paremeters as Regex , and $ is special meta-character in Regex . 由于split()方法将paremeters为Regex ,而$是特殊的元字符在Regex You need to escape the $ sign: - 您需要转义$符号:-

    System.out.println(str.split("~#\\$~")[0]);
    System.out.println(str.split("~#\\$~")[1]);

try 尝试

String s = "CT-d0712728-867d-4cc4-bd0c-b2a679b8385f~#$~2012-10-16 02:13:27 PM";

Arrays.toString(s.split("~#\\$~"))
String str = "CT-d0712728-867d-4cc4-bd0c-b2a679b8385f~#$~2012-10-16 02:13:27 PM";
String[] pieces = str.split("~#\\$~");

you can do this using String.split(). 您可以使用String.split()进行此操作。 No need to use StringTokenizer. 无需使用StringTokenizer。 See then below example. 请参见下面的示例。

String s="CT-d0712728-867d-4cc4-bd0c-b2a679b8385f~#$~2012-10-16 02:13:27 PM";
        String test[]=s.split("\\~\\#\\$\\~");
        System.out.println(test[0]);
        System.out.println(test[1]);

Let me know i you have any questions. 让我知道我有任何问题。

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

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