[英]Regex for key value pair
I have a regex 我有一个正则表达式
(\w+)\s*:((?:\w+[-+*%])*?\w+)$
that matches key value pair like these - 匹配这样的键值对-
key:value
核心价值
key2:value2
KEY2:VALUE2
But the regex match fails if the key and value are within quotes like these - 但是,如果键和值在这样的引号内,则正则表达式匹配 失败 :
"key":value
“核心价值
"key2":"value2"
“KEY2”: “值2”
What modification can be done to make the regex match key and value within quotes also ? 可以做哪些修改以使正则表达式也匹配引号内的键和值?
You can use optional quotes on either side of key-value
pairs like this: 您可以在
key-value
对的两侧使用可选的引号,如下所示:
/("?)\b(\w+)\1\s*:\s*("?)((?:\w+[-+*%])*?\w+)\b\3/g
Take note of group ("?)
that captured an empty string or a double quote. On the other side we use a back-reference \\1
of this group for closing quote. 记下捕获空字符串或双引号的组
("?)
。另一方面,我们使用该组的后向引用\\1
作为结束引号。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.