Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to split a string containing question marks and equals

Tags:

java

string

split

Having an issue where I have a java string:

String aString="name==p==?header=hello?aname=?????lname=lastname";

I need to split on question marks followed by equals.

The result should be key/value pairs:

name = "=p=="
header = "hello"
aname = "????"
lname = "lastname"

The problem is aname and lname become:

name = ""
lname = "????lname=lastname"

My code simply splits by doing aString.split("\\?",2)
which will return 2 strings.One contains a key/value pair and the second string contains the rest of the string. If I find a question mark in the string, I recurse on the second string to further break it down.

private String split(String aString)
 {
    System.out.println("Split: " + aString);
    String[] vals = aString.split("\\?",2);
    System.out.println("  - Found: " + vals.length);
    for ( int c = 0;c<vals.length;c++ )
       {
        System.out.println("  - "+ c + "| String: [" + vals[c] + "]" );
        if(vals[c].indexOf("?") > 0 )
          {
            split(vals[c]);
           }
        }
    return ""; // For now return nothing...
 }

Any ideas how I could allow a name of ?
Disclaimer: Yes , My Regex skills are very low, so I don't know if this could be done via a regex expression.

like image 673
Multiplexor Avatar asked Feb 12 '23 23:02

Multiplexor


1 Answers

You can let regex do all the heavy lifting, first splitting your string up into pairs:

String[] pairs = aString.split("\\?(?!\\?)");

That regex means "a ? not followed by a ?", which gives:

[name==p==, header=hello, aname=????, lname=lastname]

To then also split the results into name/value, split only the first "=":

String[] split = pair.split("=", 2); // max 2 parts

Putting it all together:

String aString = "name==p==?header=hello?aname=?????lname=lastname";
for (String pair : aString.split("\\?(?!\\?)")) {
    String[] split = pair.split("=", 2);
    System.out.println(split[0] + " is " + split[1]);
}

Output:

name is =p==
header is hello
aname is ????
lname is lastname
like image 54
Bohemian Avatar answered Feb 15 '23 12:02

Bohemian