0

Hava a string like this:

"let key1=value1; let key2=value2;"

I want to select the key and value as groups using regex, I've tried using look around.

/(\w+)(?=\=)(\w+);/g

but it doesn't work with me, any suggestions?

Wiktor Stribiżew
  • 561,645
  • 34
  • 376
  • 476

3 Answers3

0

The following regex should do the trick: (let (\w+) ?= ?(\w+);?)+. Each let statement will be a match where the key will be the group 2 and the value the group 3.

Samuel Martineau
  • 127
  • 1
  • 1
  • 10
0

The (?=\=) expression part is a lookahead, a zero-width assertion, it does not consume text but requires it to be present on the right. When you say (?=\=)(\w+) you want \w+ pattern to start matching on =. As \w does not match =, your regex always fails.

Use

/(\w+)=(\w+);/g

JavaScript (borrowed from How do you access the matched groups in a JavaScript regular expression?):

var myString = "let key1=value1; let key2=value2;";
var myRegexp = /(\w+)=(\w+);/g;
match = myRegexp.exec(myString);
while (match != null) {
  console.log(match[1] + "," + match[2]);
  match = myRegexp.exec(myString);
}
Ryszard Czech
  • 16,363
  • 2
  • 17
  • 35
-2

To be more specific, we could use (\w+) ?= ?(\w+);?+

Pavan J
  • 345
  • 1
  • 3
  • 12