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
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:
Let’s break down the components of this regex:
(?<!wAmys)
: Negative lookbehind assertion. It asserts that whatprecedes the current position is not a word character
(w)
followedby "Amy" and a whitespace character
(s)
.b
: Word boundary, ensures that we match whole words and not partialmatches.
(d{2,3})
: Capturing group for 2 or 3 digits.b
: Another word boundary.(?!scm)
: Negative lookahead assertion. It asserts that what followsthe current position is not a whitespace character followed by "cm".
In JavaScript, you can use this regex as follows:
This will output:
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".
I only ignore any pronoun and the sentence has to be structured like you wrote it