Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why split method does not support $,* etc delimiter to split string

Tags:

java

regex

import java.util.StringTokenizer;
class MySplit
{
  public static void main(String S[])
  {
    String settings = "12312$12121";
    StringTokenizer splitedArray = new StringTokenizer(settings,"$");

    String splitedArray1[] = settings.split("$");
        System.out.println(splitedArray1[0]);

    while(splitedArray.hasMoreElements())
        System.out.println(splitedArray.nextToken().toString());            
  }
}

In above example if i am splitting string using $, then it is not working fine and if i am splitting with other symbol then it is working fine.

Why it is, if it support only regex expression then why it is working fine for :, ,, ; etc symbols.

like image 493
Vinay Sharma Avatar asked Dec 08 '22 03:12

Vinay Sharma


2 Answers

$ has a special meaning in regex, and since String#split takes a regex as an argument, the $ is not interpreted as the string "$", but as the special meta character $. One sexy solution is:

settings.split(Pattern.quote("$"))

Pattern#quote:

Returns a literal pattern String for the specified String.

... The other solution would be escaping $, by adding \\:

settings.split("\\$")

Important note: It's extremely important to check that you actually got element(s) in the resulted array.

When you do splitedArray1[0], you could get ArrayIndexOutOfBoundsException if there's no $ symbol. I would add:

if (splitedArray1.length == 0) {
    // return or do whatever you want 
    // except accessing the array
}
like image 103
Maroun Avatar answered Jan 20 '23 16:01

Maroun


If you take a look at the Java docs you could see that the split method take a regex as parameter, so you have to write a regular expression not a simple character.

In regex $ has a specific meaning, so you have to escape it this way:

settings.split("\\$");
like image 25
mcamier Avatar answered Jan 20 '23 16:01

mcamier