简体   繁体   中英

Regular expression to split key=value

I have a string like this:

KEY1=Value1, KE_Y2=[V@LUE2A, Value2B], Key3=, KEY4=V-AL.UE4, KEY5={Value5}

I need to split it to get a Map with key-value pairs. Values in [] should be passed as a single value ( KE_Y2 is a key and [V@LUE2A, Value2B] is a value).

What regular expression should I use to split it correctly?

There's a magic regex for the first split:

String[] pairs = input.split(", *(?![^\\[\\]]*\\])");

Then split each of the key/values with simply "=":

for (String pair : pairs) {
    String[] parts = pair.split("=");
    String key = parts[0];
    String value = parts[1];
}

Putting it all together:

Map<String, String> map = new HashMap<String, String>();
for (String pair : input.split(", *(?![^\\[\\]]*\\])")) {
    String[] parts = pair.split("=");
    map.put(parts[0], parts[1]);
}

Voila!


Explanation of magic regex:

The regex says "a comma followed by any number of spaces (so key names don't have leading blanks), but only if the next bracket encountered is not a close bracket"

How about this:

Map<String, String> map = new HashMap<String, String>();
Pattern regex = Pattern.compile(
    "(\\w+)        # Match an alphanumeric identifier, capture in group 1\n" +
    "=             # Match =                                             \n" +
    "(             # Match and capture in group 2:                       \n" +
    " (?:          # Either...                                           \n" +
    "  \\[         #  a [                                                \n" +
    "  [^\\[\\]]*  #  followed by any number of characters except [ or ] \n" +
    "  \\]         #  followed by a ]                                    \n" +
    " |            # or...                                               \n" +
    "  [^\\[\\],]* #  any number of characters except commas, [ or ]     \n" +
    " )            # End of alternation                                  \n" +
    ")             # End of capturing group", 
    Pattern.COMMENTS);
Matcher regexMatcher = regex.matcher(subjectString);
while (regexMatcher.find()) {
    map.put(regexMatcher.group(1), regexMatcher.group(2));
} 

Start with @achintya-jha's answer. When you split a String, it will give you an array (or something that acts like it) so you can iterate throught the pair of key/value and then you do the second split which is supposed to give you another array of size 2; you then use the first element as the key and the second as the value.

EDIT:

I dind't found useful link for what I meant (see the comments on the question) in JAVA, (there is plenty of them for C/C++ though) so I wrote it:

Map<String, String> map = new HashMap<String, String>();
String str = "KEY1=Value1, KE_Y2=[V@LUE2A, Value2B]], Key3=, KEY4=V-AL.UE4, KEY5={Value5}";     


final String openBrackets =  "({[<";
final String closeBrackets = ")}]>";

String buffer = "";
int state = 0;
int i = 0;      
Stack<Integer> stack = new Stack<Integer>(); //For the brackets

String key = "";


while(  i < str.length() ) {

    char c = str.charAt(i);


    //Skip any whitespace
    if( " \t\n\r".indexOf(c) > -1 ) {
        ++i;
        continue;
    }


    switch(state) {

    //Reading Key
    case 0:
        if( c != '=' ) {
            buffer += c;
        } else {
            //Go read a value.
            key = buffer;
            state = 1;
            buffer = "";
        }
        ++i;
        break;

    //Reading value
    case 1:

        //Opening bracket
        int pos = openBrackets.indexOf(c);
        if( pos != -1 ) {
            stack.push(pos);
            ++i;
            break;
        }

        //Closing bracket
        pos = closeBrackets.indexOf(c);
        if( pos != -1 ) {

            if( stack.size() == 0 ) {
                throw new RuntimeException("Syntax error: Unmatched closing bracket '" + c + "'" );
            }

            int pos2 = stack.pop();
            if( pos != pos2 ) {
                throw new RuntimeException("Syntax error: Unmatched closing bracket, expected a '"
                        + closeBrackets.charAt(pos2) + "' got '" + c );             
            }
            ++i;
            break;
        }

        //Handling separators 
        if( c == ',' ) {
            if( stack.size() == 0 ) {
                //Put the pair in the map.
                map.put(key, buffer);

                //Go read a new Key.
                state = 0;
                buffer = "";
                ++i;
                break;
            }                       
        }

        //else
            buffer += c;
            ++i;


        } //switch
} //while
  1. split the given string with String.split(",");
  2. Now split each element of the array with String.split("=");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM