0

I'm using python regex on these two strings:

t1 = 'foo 36 months bar'

t2 = 'bar Not suitable for children under 36 months foo'

I want to match '36 months' on t1, and not match t2 because it has 'Not suitable for children under' before the '36 months.

After searching I have this:

regex = re.compile(r'((?!Not suitable for children under) 36 month)')

But it matches both. How do adapt this so it doesn't match a string with 'Not suitable for children under' before the ' 36 months'?

many thanks

1 Answer 1

2

What you're doing is a negative lookahead.
However, what you're trying to find is when some text exists before what you want to match.
So instead use a negative lookbehind:

re.search('(?<!Not suitable for children under) 36 months',t1) 

Demonstration:

In [13]: re.search('(?<!Not suitable for children under) 36 months',t1)                             
Out[13]: <re.Match object; span=(3, 13), match=' 36 months'>

In [14]: re.search('(?<!Not suitable for children under) 36 months',t2)                             

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.