0

I have the following string, from which I want to extract the value of the key2 which is value2

[key1=value1,key2=value2,key3=value3]

I tried giving the following regex ,key2=(.*),\w+but it is extracting ,key2=value2,key3but I am want only the value value2

What regex can be used for this one?

tintin
  • 5,676
  • 15
  • 68
  • 97
  • 1
    You already captured the value you need, it is in Group 1. What tool/programming language are you using? – Wiktor Stribiżew Aug 11 '17 at 08:12
  • your answer is in group1, you should use the regex key2=(\w+) – marvel308 Aug 11 '17 at 08:18
  • If you use 'key2=(.*),' , you result is 'key2=value2'. I think you should substring the result to get the result that you want. Regards, – Nyein Mon Soe Aug 11 '17 at 08:23
  • As answered above, your result is in group 1. How to retrieve it depends on the language/tool you're using. I'd also advise you to use `,key2=(.*?),\w+` to make sure you don't capture more than you need. `?` means you want the shortest string that matches. – pchaigno Aug 11 '17 at 08:25
  • `(.*?),\w+` will not match the *shortest* string, but up to the leftmost occurrence of `,\w+` subpattern. I.e. if there are multiple `,key2=` in the string, the match will include its first occurrence and then all up to the first `,\w+=`. That is why the best regex here is `(?:,|^)key2=(\w*)`, or - if there is no way to grab Group 1 value, there are options like `(?:,|^)key2=\K\w*` or `(?<=,key2=)\w*`. – Wiktor Stribiżew Aug 11 '17 at 08:37
  • Hi guys, If I try `(?:,|^)key2=(\w*)` or key2=(\w+) in regexr.com, the whole of the `,key2=value2` is getting highlighted. I was expecting only the capturing group with value `value2` to be highlighted. – tintin Aug 11 '17 at 10:55

1 Answers1

0

With a lookbehind you should solve the problem:

(?<=(?:key2=))\w+
leoinstack
  • 26
  • 3