4

我有一个这样的字符串:

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

我需要拆分它以获取带有键值对的 Map。中的值[]应作为单个值传递(KE_Y2是键和[V@LUE2A, Value2B]值)。

我应该使用什么正则表达式来正确拆分它?

4

4 回答 4

9

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"

于 2013-04-19T08:10:28.983 回答
4

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));
} 
于 2013-04-19T08:10:50.993 回答
-1

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
于 2013-04-19T08:09:13.537 回答
-2
  1. 用 String.split(","); 分割给定的字符串
  2. 现在用 String.split("="); 分割数组的每个元素;
于 2013-04-19T08:00:45.620 回答