skip to Main Content

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

2

Answers


  1. Chosen as BEST ANSWER

    With help from @user24714692 I've found a few more variations that work too!

    const str = `abcde 9'2" abcde 8' abcde 7' 11" abcde`
    
    const regexes = [
      /[0-9]+'(?:s*[0-9]+")?/g,
      /d+'(?: *d+")?/g,
      /d+'(?: ?d+")?/g
    ]
    
    for (let regex of regexes) {
      const matches = [...str.matchAll(regex)]
    
      const actual = matches.map(x => x[0])
      const expected = [ `9'2"`, `8'`, `7' 11"` ]
    
      console.log(actual)
      
      // tests
      console.log(actual[0] === expected[0]) // true
      console.log(actual[1] === expected[1]) // true
      console.log(actual[2] === expected[2]) // true
    }


  2. 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]); 
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search