Home > other >  Extracting `<key>:<value>` pairs with regex
Extracting `<key>:<value>` pairs with regex

Time:11-18

there is a textarea and want to extract with key:value (something like below image)

enter image description here

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"

CodePudding user response:

You 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))
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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-commas (captured in Group 2), "
    • | - or
    • (\S ) - Group 3: one or more non-whitespaces chars.

CodePudding user response:

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"
  • Related