Powered by Blogger.

Java - Unable to Split a String on Caret (^) symbol as a delimiter

>> Saturday, July 29, 2017

In Java Regular Expressions , Caret ( ^ ) is a Special character. Here it means "it should match the beginning" of an input.
Split method using the Caret symbol on String


You we 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 "\\^".
String[] substr = str.split("\\^");
package com.string;
//javabynataraj.blogspot.com
public class SplitCaret {
 public static void main(String[] args) {
 String str = "I^am^learning^java";
 String[] substr = str.split("\\^");
 for(String st: substr){
  System.out.println(st);
  }
 }
}
Output:




Related Posts Plugin for WordPress, Blogger...
© javabynataraj.blogspot.com from 2009 - 2022. All rights reserved.