-2

I have a string, which contains ^ symbol given below.

String tempName = "afds^afcu^e200f.pdf"

I want to split it like below

[afds, afcu, e200f]

How to resolve this.

M. Deinum
  • 115,695
  • 22
  • 220
  • 224
Roy
  • 33
  • 1
  • 11

4 Answers4

2

The parameter to split() is a regular expression, which has special meta-characters. If the delimiter you're splitting on contains those special characters (e.g. ^), you have two options:

  • Escape the characters using \, which has to be doubled in a Java string literal to \\:

    String[] result = tempName.split("\\^");
    
  • If you don't want to bother with that, or if the delimiter is dynamically assigned at runtime, so you can't escape the special characters yourself, call Pattern.quote() to do it for you:

    String[] result = tempName.split(Pattern.quote("^"));
    
Andreas
  • 154,647
  • 11
  • 152
  • 247
1

you need to add \\ in split method of String to split the string by this (^), because ^ is an special character in regular expression and you need to omit it with \\:

String tempName = "afds^afcu^e200f.pdf";
String [] result = tempName.split("\\^");
System.out.println(Arrays.toString(result));

Java characters that have to be escaped in regular expressions are: .[]{}()<>*+-=!?^$|

Two of the closing brackets (] and }) are only need to be escaped after opening the same type of bracket. In []-brackets some characters (like + and -) do sometimes work without escape.

more info...

Mustafa Poya
  • 2,615
  • 5
  • 22
  • 36
0

String.split() in Java takes a regular expression. Since ^ is a control character in regex (when at the beginning of the regex string it means "the start of the line"), we need to escape it with a backslash. Since backslash is a control character in Java string literals, we also need to escape that with another backslash.

String tempName = "afds^afcu^e200f.pdf";
String[] parts = tempName.split("\\^");
Green Cloak Guy
  • 23,793
  • 4
  • 33
  • 53
0

You can use the retrieve a substring without the file extension and split that according to the delimiter that is required (^). This is shown below:

public static void main(String[] args) {
        String tempName = "afds^afcu^e200f.pdf";
        String withoutFileFormat = tempName.substring(0, tempName.length() - 4); //retrieve the string without the file format
        String[] splitArray = withoutFileFormat.split("\\^"); //split it using the "^", use escape characters
        
        System.out.println(Arrays.toString(splitArray)); //output the result
       
    }

Required Output:

[afds, afcu, e200f]