Search code examples
regexregular-language

Regular expression to perform following operation


Input string contains multiple key[with some value], which we need to replace with key[with some value],val[value which is same as key].

Input string:

...key[102]...key[108]... key[211]...

Output string:

... key[102],val[102]...key[108],val[108]...key[211],val[211]...

Basically I need to replace all the key with values inside square braces with key[value],val[same value].

E.g. key[102]key[102],val[102], and key[108]key[108],val[108].


Solution

  • You need to use capturing groups.( http://www.regular-expressions.info/brackets.html )

    key\[(.*?)\]
    

    Regular expression visualization

    Debuggex Demo

    Example java code (i couldn't test it):

    var str = "...key[102]...key[108]... key[211]...";
    System.out.println( (str.replaceAll("key\\[(.*?)\\]", "key[$1],val[$1]") );