Java split on ^ (caret?) not working, is this a special character?

匿名 (未验证) 提交于 2019-12-03 00:44:02

问题:

In Java, I am trying to split on the ^ character, but it is failing to recognize it. Escaping \^ throws code error.

Is this a special character or do I need to do something else to get it to recognize it?

String splitChr = "^"; String[] fmgStrng = aryToSplit.split(splitChr); 

回答1:

The ^ is a special character in Java regex - it means "match the beginning" of an input.

You will need to escape it with "\\^". The double slash is needed to escape the \, otherwise Java's compiler will think you're attempting to use a special \^ sequence in a string, similar to \n for newlines.

\^ is not a special escape sequence though, so you will get compiler errors.

In short, use "\\^".



回答2:

The ^ matches the start of string. You need to escape it, but in this case you need to escape it so that the regular expression parser understands which means escaping the escape, so:

String splitChr = "\\^"; ...

should get you what you want.



回答3:

String.split() accepts a regex. The ^ sign is a special symbol denoting the beginning of the input sequence. You need to escape it to make it work. You were right trying to escape it with \ but it's a special character to escape things in Java strings so you need to escape the escape character with another \. It will give you:

\\^


回答4:

use "\\^". Use this example as a guide:

    String aryToSplit = "word1^word2";     String splitChr = "\\^";     String[] fmgStrng = aryToSplit.split(splitChr);      System.out.println(fmgStrng[0]+","+fmgStrng[1]);

It should print "word1,word2", effectively splitting the string using "\\^". The first slash is used to escape the second slash. If there were no double slash, Java would think ^ was an escape character, like the newline "\n"



回答5:

None of the above answers makes no sense. Here is the right explanation.

  1. As we all know, ^ doesn't need to be escaped in Java String.
  2. As ^ is special charectar in RegulalExpression , it expects you to pass in \^
  3. How do we make string \^ in java? Like this String splitstr = "\^"

Please let me know this explanation helps. Please bear with typos if any.

Thanks -karuna



回答6:

String[] fmgStrng = aryToSplit.split("\\\^"); 


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