admin管理员组文章数量:1421582
there is a textarea and want to extract with key:value
(something like below image)
I have a regex but not working as expected
/([^\s][a-zA-Z!]+:(\s)?"?([a-z0-9\s.]+)"?[^ $])/gi
if the user enters the below string at that time regex break the group key:value
.
is:"browser" browser: "chrome 11.11 V" node: error type:"Error"
expected group:
is:"browser"
browser: "chrome 11.11 V"
node: error
type:"Error"
there is a textarea and want to extract with key:value
(something like below image)
I have a regex but not working as expected
/([^\s][a-zA-Z!]+:(\s)?"?([a-z0-9\s.]+)"?[^ $])/gi
if the user enters the below string at that time regex break the group key:value
.
is:"browser" browser: "chrome 11.11 V" node: error type:"Error"
expected group:
is:"browser"
browser: "chrome 11.11 V"
node: error
type:"Error"
Share
Improve this question
edited Nov 17, 2021 at 8:33
Archin Modi
asked Nov 17, 2021 at 7:57
Archin ModiArchin Modi
5122 gold badges9 silver badges20 bronze badges
4
-
1
Try
/(\w+)=\s*(?:"([^"]*)"|(\S+))/
- Group 1 will contain the key, Group 2 or Group 3 will contain the value. – Wiktor Stribiżew Commented Nov 17, 2021 at 8:03 - @WiktorStribiżew not working, I've updated the question. – Archin Modi Commented Nov 17, 2021 at 8:11
-
Replace
=
with:
and it will work. – Wiktor Stribiżew Commented Nov 17, 2021 at 8:16 - See my answer proving it works. – Wiktor Stribiżew Commented Nov 17, 2021 at 8:46
2 Answers
Reset to default 2You can use
const text = 'is:"browser" browser: "chrome 11.11 V" node: error type:"Error"';
const re = /(\w+):\s*(?:"([^"]*)"|(\S+))/g;
let dict = {}, m;
while(m = re.exec(text)) {
dict[m[1]]=(m[3] || m[2]);
}
console.log(dict);
// Or just get all matches:
console.log(text.match(re))
See the regex demo. Details:
(\w+)
- Group 1: one or more word chars:
- a colon\s*
- zero or more whitespaces(?:"([^"]*)"|(\S+))
- either of"([^"]*)"
-"
, 0+ non-mas (captured in Group 2),"
|
- or(\S+)
- Group 3: one or more non-whitespaces chars.
Regex:
/([a-zA-Z!]+:\s*[" ]?([a-z0-9\s.]+)[" $])/gi
Text:
sdfd:"dsffs" dsfd: "dsf demo" sfd: dsf fdsff:"fdsfsdf"
List:
sdfd:"dsffs"
dsfd: "dsf demo"
sfd: dsf
fdsff:"fdsfsdf"
本文标签: javascriptExtracting ltkeygtltvaluegt pairs with regexStack Overflow
版权声明:本文标题:javascript - Extracting `<key>:<value>` pairs with regex - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745352035a2654826.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论