3

I have a sample data following:

***^|^100^|^101^|^102^|^103^|^104^|^

I wish to split by "^|^" so the result will be:

***
100
101
102
103
104

Below is my sample code, but failed to obtain expected result,am i misunderstood the split pattern?

String a = "***^|^100^|^101^|^102^|^103^|^104^|^105^|^106^|^107^|^108^|^";
String [] split ;

split = a.split("^|^");
for(int i=0; i<split.length; i++)
{
        System.out.println(split[i]);
}
hades
  • 4,294
  • 9
  • 46
  • 71

3 Answers3

12

Both ^ and | are special-chatacters you need to escape them.

split = a.split("\\^\\|\\^");
Uma Kanth
  • 5,659
  • 2
  • 20
  • 41
12

Use Pattern.quote() to treat all meta characters as String literals / Literal pattern. ^ , | have special meaning in regex.

This should work :

public static void main(String[] args) throws Exception {
    String s = "***^|^100^|^101^|^102^|^103^|^104^|^";
    String pattern = Pattern.quote("^|^");
    System.out.println(Arrays.toString(s.split(pattern)));

}

O/P :

[***, 100, 101, 102, 103, 104]
TheLostMind
  • 35,966
  • 12
  • 68
  • 104
  • 1
    I had no idea about Pattern. Thanks looks awesome. – Michael Queue Nov 13 '15 at 06:06
  • 2
    That looks much nicer than the usual backslash frenzy. Still, I wished there was a split method that takes a separator string, not a regex. – Thilo Nov 13 '15 at 06:07
  • @Thilo - Ya. That would have made things much simpler :) – TheLostMind Nov 13 '15 at 06:08
  • 1
    and if you use that same pattern in more than one place, you can declare it once for all to use `public static final Pattern HAT_PIPE_HAT = Pattern.quote("^|^")` – Thilo Nov 13 '15 at 06:10
  • 1
    @Thilo - `Pattern.quote()` returns a `String`. But Yes, you are right, creation of Patterns is costly :) – TheLostMind Nov 13 '15 at 06:14
  • 2
    I was thinking more about readibility. I don't think it's that costly. But one could take it one step further and do `static final Pattern HAT_PIPE_HAT = Pattern.compile(Pattern.quote("^|^"))` which gives `HAT_PIPE_HAT.split(theString)`. – Thilo Nov 13 '15 at 07:05
  • @Thilo - Yep. Making patterns `static` and `final` improve readability as well as *reusability* :) – TheLostMind Nov 13 '15 at 07:51
-2

Please check this

String str = "***^|^100^|^101^|^102^|^103^|^104^|^";
String arr[] = str.split("\\^\\|\\^");
System.out.println(arr.length);
Ashish Agrawal
  • 1,977
  • 2
  • 18
  • 32