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?
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?
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.
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);
}