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
  • 607,720
  • 39
  • 448
  • 563
DanTe
  • 115
  • 6

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
  • 143
  • 1
  • 1
  • 11
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
  • 18,032
  • 4
  • 24
  • 37
-2

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

Pavan J
  • 353
  • 1
  • 3
  • 12