How to split the string using '^' this special character in java?

后端 未结 3 913
北恋
北恋 2020-12-03 15:06

I want to split the following string \"Good^Evening\" i used split option it is not split the value. please help me.

This is what I\'ve been trying:



        
相关标签:
3条回答
  • 2020-12-03 15:09

    I'm assuming you did something like:

    String[] parts = str.split("^");
    

    That doesn't work because the argument to split is actually a regular expression, where ^ has a special meaning. Try this instead:

    String[] parts = str.split("\\^");
    

    The \\ is really equivalent to a single \ (the first \ is required as a Java escape sequence in string literals). It is then a special character in regular expressions which means "use the next character literally, don't interpret its special meaning".

    0 讨论(0)
  • 2020-12-03 15:11

    The regex you should use is "\^" which you write as "\\^" as a Java String literal; i.e.

    String[] parts = "Good^Evening".split("\\^");
    

    The regex needs a '\' escape because the caret character ('^') is a meta-character in the regex language. The 2nd '\' escape is needed because '\' is an escape in a String literal.

    0 讨论(0)
  • 2020-12-03 15:11

    try this

    String str = "Good^Evening";
    String newStr = str.replaceAll("[^]+", "");
    
    0 讨论(0)
提交回复
热议问题