skip to Main Content

Well, I’ve a Multiline Text like below. I want to extract the first Matched Content value (Here, 10) after Messi: using JavaScript Regular Expressions. The Matching String (Messi: ) Can be on any line.

Neymar: 11
Messi: 10
Ronaldo: 7
Chhetri: 11
Messi: 18

–Thanks In Advance.

3

Answers


  1. You can use the following pattern.

    /Messi: (.+?)$/m
    

    The $ will match the end of the line, so this will capture everything up to it.

    Example

    var string = `Neymar: 11
    Messi: 10
    Ronaldo: 7
    Chhetri: 11
    Messi: 18`
    
    var matches = string.match(/Messi: (.+?)$/m)
    
    console.log(matches[1])
    Login or Signup to reply.
  2. This function finds the value of a key of choice:

    const input = `Neymar: 11
    Messi: 10
    Ronaldo: 7
    Chhetri: 11
    Messi: 18`
    
    function findValue(str, key) {
      const regex = new RegExp('\b' + key + ': ([^\n]*)');
      const matches = str.match(regex);
      return matches ? matches[1] : null;
    }
    
    let value = findValue(input, 'Messi');
    console.log('Messi =>', value);
    
    value = findValue(input, 'Foo');
    console.log('Foo =>', value);

    Output:

    Messi => 10
    Foo => null
    

    Explanation of regex constructor:

    • '\b' — word boundary
    • + key + — dynamically concatenate key
    • ': ([^\n]*)' — expect a colon, a space, and capture everything after that up to the next newline
    Login or Signup to reply.
  3. wouldn’t it be better to parse this string once into some data-structure and then use that instead of messing around with regexes.

    const str = `
    Neymar: 11
    Messi: 10
    Ronaldo: 7
    Chhetri: 11
    Messi: 18
    `;
    
    const data = Object.fromEntries(
      str.split("n") // get rows
        .filter(v => v.trim()) // remove empty rows
        .map(row => { // parse row
          const [k, v] = row.split(":", 2);
          return [k.trim(), parseFloat(v)]
        })
    );
    
    console.log("data", data);
    console.log("data.Messi", data["Messi"]);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search