Search code examples
javascriptregex

How can I extract all desired values from string with regex groups?


I have a string:

const str = `abcde 9'2" abcde 8' abcde 7' 11" abcde`

I'm trying to extract these values:

[ "9'2", "8'", "7' 11" ]

I want to use regex groups to achieve this (my actual code is far more complex and regex groups will simplify things) but my regex is not quite working. How can I make all 3 tests return true in the code snippet below?

const str = `abcde 9'2" abcde 8' abcde 7' 11" abcde`

const regex = /(\d+' ?\d+)"/g

const matches = [...str.matchAll(regex)]

const actual = matches.map(x => x[1])

const expected = [ "9'2", "8'", "7' 11" ]

console.log(actual) // [ "9'2", "7' 11" ]

// tests
console.log(actual[0] === expected[0]) // true
console.log(actual[1] === expected[1]) // false
console.log(actual[2] === expected[2]) // false


Solution

  • You can use this pattern:

    [0-9]+'(?:\s*[0-9]+")?
    

    const str = `abcde 9'2" abcde 8' abcde 7' 11" abcde`;
    
    const regex = /[0-9]+'(?:\s*[0-9]+")?/g;
    
    const matches = [...str.matchAll(regex)];
    
    const actual = matches.map((x) => x[0]);
    const expected = [`9'2"`, `8'`, `7' 11"`];
    
    console.log(actual[0] === expected[0]); 
    console.log(actual[1] === expected[1]); 
    console.log(actual[2] === expected[2]);