Java exception for using String.Split() method: Dangling meta character

I’m trying to parse a URL string (which I am receiving via HTML Get method) and extract the embedded options. I’m wondering why it drops an exception on s=s.split("?")[0];

Exception in thread "main" java.util.regex.PatternSyntaxException: Dangling meta character '?' near index 0

public static void main(String[] args) {
    String s= "run.html?yse=yse1&tracefile=capacity.1Mbps_c50.txt&fd=100&rd=100&down=1&up=1&per=0.00001";
    s=s.split("?")[0];  //drops error
    String ss[]=s.split("&");
//this is a class I have that receives the array of splitted options.
    JavaRunEmulator j = new JavaRunEmulator(ss);
    System.out.println(j.getOutput());
}

Answer

From the documentation the split() method takes a regular expression as an input.

public String[] split(String regex)

Splits this string around matches of the given regular expression.

The character ? is used to identify certain patterns in regex, including some of the following

Greedy quantifiers
X? : X, once or not at all

Reluctant quantifiers
X?? : X, once or not at all
X*? : X, zero or more times
X+? : X, one or more times
X{n}? : X, exactly n times
X{n,}? : X, at least n times
X{n,m}? : X, at least n but not more than m times

Possessive quantifiers
X?+ : X, once or not at all

If you escape the string like this

s=s.split("\?")[0];

the ? won’t be treated like it is being used in a pattern and is instead a raw string.

Leave a Reply

Your email address will not be published. Required fields are marked *