Match key-value pattern regex

后端 未结 2 560
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-22 13:57

I am making a key-value parser where the input string takes the form of key:\"value\",key2:\"value\". Keys can contain the characters a-z, A-Z

2条回答
  •  无人及你
    2021-01-22 14:37

    You could use the below regex to get the key value pair.

    ([a-zA-Z0-9]+):"(.*?)(?

    OR

    ([a-zA-Z0-9]+):"(.*?)"(?=,[a-zA-Z0-9]+:"|$)
    

    DEMO

    Java regex would be,

    "([a-zA-Z0-9]+):\"(.*?)(?

    (? negative lookbehind asserts that the double quotes won't be preceeded by a backslash character. In java, to match a backslash character, you need to escape the backslash in your pattern exactly three times, ie, \\\\

    DEMO

    String s = "joe:\"Look over there\\, it's a shark!\",sam:\"I like fish.\"";
    
    Matcher m = Pattern.compile("([a-zA-Z0-9]+):\"(.*?)(? " + m.group(2));
        }
    }
    

    Output:

    joe --> Look over there\, it's a shark!
    sam --> I like fish.
    

    OR

    String s = "joe:\"Look over there\\, i\\\"t's a shark!\",sam:\"I like fish.\"";
    
    Matcher m = Pattern.compile("([a-zA-Z0-9]+):\"((?:\\\\\"|[^\"])*)\"").matcher(s);
        while(m.find())
        {
            System.out.println(m.group(1) + " --> " + m.group(2));
        }
    }
    

    Output:

    joe --> Look over there\, i\"t's a shark!
    sam --> I like fish.
    

提交回复
热议问题