skip to Main Content

str:

"There was Amy. Amy was 16 years old and she was 167 cm tall.
And also there was Jason. Jason was 18 years old and he was 185 cm tall"

Regex to match Amy’s age and height, but not to match Jason’s.

So:

16 - match 
167 - match 
18 - no match 
185 - no match

I thought about regex to search for d{2,3} and look-around word ‘Amy’ but I can’t figure it out. Also word ‘Amy’ can’t match.

If it can’t be done in single expression I would also love to see it in JavaScript with extra logic.

2

Answers


  1. Hope It will work & solve your problem.

    You can use a combination of lookbehind and lookahead assertions in your regular expression to achieve this. Here’s a regex for your specific case:

    (?<!wAmys)b(d{2,3})b(?!scm)
    

    Let’s break down the components of this regex:

    1. (?<!wAmys): Negative lookbehind assertion. It asserts that what
      precedes the current position is not a word character (w) followed
      by "Amy" and a whitespace character (s).
    2. b: Word boundary, ensures that we match whole words and not partial
      matches.
    3. (d{2,3}): Capturing group for 2 or 3 digits.
    4. b: Another word boundary.
    5. (?!scm): Negative lookahead assertion. It asserts that what follows
      the current position is not a whitespace character followed by "cm".

    In JavaScript, you can use this regex as follows:

    const regex = /(?<!wAmys)b(d{2,3})b(?!scm)/g;
    const input = "There was Amy. Amy was 16 years old and she was 167 cm tall. And also there was Jason. Jason was 18 years old and he was 185 cm tall";
    
    let match;
    while ((match = regex.exec(input)) !== null) {
      console.log(match[1]);
    }
    

    This will output:

    16
    167
    

    This ensures that the regex matches 2 or 3 digit numbers that are not directly preceded by the word "Amy" and are not followed by "cm".

    Login or Signup to reply.
  2. I only ignore any pronoun and the sentence has to be structured like you wrote it

    const getNameAgeHeight = (str, name) => {
      const regex = new RegExp(`${name}\s+was\s+(\d+)\s+years\s+old\s+and\s+.*?\s+was\s+(\d+)\s+cm\s+tall`, "i");
      const match = str.match(regex);
    
      if (match) {
        const [_, age, height] = match;
        return { name, age, height };
      }
      return null; // nothing found
    }
    
    const str = "There was Amy. Amy was 16 years old and she was 167 cm tall. And also there was Jason. Jason was 18 years old and he was 185 cm tall";
    let name = "Amy";
    console.log(getNameAgeHeight(str, name))
    
    name = "Jason";
    console.log(getNameAgeHeight(str, name))
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search