0

'"key":"value"' I have the following string and I want to strip out key and value. What should be the regex for this?

/"(.*?)"/g returns "key" and "value". I am interested in key and value without the "s.

Any pointer would be helpful.

Sarbbottam
  • 5,410
  • 4
  • 30
  • 41
  • It's pretty unlikely this is the right way to do this. You're probably dealing with JSON. In that case, just parse the JSON, as in `JSON.parse('{"key":"value"}')`. – elixenide Feb 08 '16 at 18:39
  • `var str = '"key":"value"'; var obj = JSON.parse("{" + str + "}"); var key = Object.keys(obj)[0]; var val = obj[key]; console.log(key, val);` – epascarello Feb 08 '16 at 18:41
  • If you still want a regex, `/"(.+)":"(.+)"/` should do the work. – kevinkl3 Feb 08 '16 at 18:42
  • So from that trivial answer linked, it looks like `".*?"` is the mindless way to do it. –  Feb 08 '16 at 18:58
  • @sln `/"(.*?)"/g` returns `"key"` and `"value"`. I am interested in `key` and `value` w/o the `"` – Sarbbottam Feb 08 '16 at 19:05
  • @sarbbottam - I can only assume you are new to regular expressions. `I am interested in ..` is why there are capture groups. –  Feb 08 '16 at 19:09
  • `/[^":]+/g` might work – Joseph Marikle Feb 08 '16 at 19:12
  • @sln you are correct, I am new to regex and thus struggling. – Sarbbottam Feb 08 '16 at 19:12
  • to explain my commenet further: `[...]` creates a character class. `[^...]` makes it a negative match (exclude any `"` and `:` characters). `+` means one or more characters to match. `g` means make it global. – Joseph Marikle Feb 08 '16 at 19:14
  • Thanks @JosephMarikle `/([^":]+)/g` captures every thing w/o `"`. My string is not exactly `'"key":"value"'` but `' "key": "value",'` – Sarbbottam Feb 08 '16 at 19:17
  • @sarbbottam - Capture groups _capture_ the sub-expression data within the parenthesis. They are numbered sequentially from left to right as found in your expression. You can access them after the match via some index 1,2,3, etc. _Capture Group 0_ is a special buffer than contains the entire match. Example `"(.*?)"`, here group 0 contains `"key"` and group 1 contains `key`. –  Feb 08 '16 at 19:18
  • If it means anything, `(?<=").*?(?=")` would make group 0 now contain `key`. But, like a jacked up regex engine JS uses, there are no lookbehind assertions, so `(?<=")` will throw an error. Accept that you always have to work around this messed up engine. Use the capture groups, and try not to get disgusted ! –  Feb 08 '16 at 19:22
  • Thanks @sln, I guess I have use `/"(.*?)"/g` and then strip off `"`. – Sarbbottam Feb 08 '16 at 19:25

0 Answers0