简体   繁体   中英

select the key and the value without the equal using regex

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM