Home > Back-end >  Regex to extract text from a paragraph
Regex to extract text from a paragraph

Time:10-13

Say I have this text string

key: "abc", value: "def"

and I want to get only the text after key: -- so output should be "abc" inclusive of the quotes. How do I get this?

I've tried this but it does not work

key: (.*),

CodePudding user response:

Your regex seems to be correct but it may not work if you have, at the end. You need to make sure it matches first , after you start.

const regex = /key: (\"[^",] \"),/gm;

// Alternative syntax using RegExp constructor
// const regex = new RegExp('key: (\\"[^",] \\"),', 'gm')

const str = `key: "abc", value: "def",`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex  ;
    }
    
    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}

To parse/extract content from JSON best would be to use JSON.parse.

const data = JSON.parse('{key: "abc", value: "def"}');
console.log('"'   data.key   '"');

CodePudding user response:

You can try

\bkey\s*:\s*(.*?)\s*(?:,|$)

const text = 'key: "abc", value: "def"';

const key = text.match(/\bkey\s*:\s*(.*?)\s*(?:,|$)/)?.[1];

console.log(key);

  • Related