0

Let's suppose we have the string "rice with milk" and another one like "white rice". I want to use a regex to take the second string, or whatever string which have "rice" in it but no "rice with". Talking in sets that would be the set of all the strings that contains "rice" but not "rice with"

I've been trying with extending the functionality of ^ to words and not only to characters, playing with | and groups but I can't find the solution.

2
  • To clarify: you need a Python compatible regex that matches a string that has rice not followed by space followed by with. Is my understanding correct? Commented Oct 15, 2013 at 3:43
  • That's correct, I do want strings with rice not followed by space followed by with Commented Oct 15, 2013 at 3:46

2 Answers 2

3

You should be able to do this using "negative lookahead":

import re
m1 = re.search('rice(?! with)', 'rice with beans')
m2 = re.search('rice(?! with)', 'white rice is delicious')
if m1:
  print 'm1 matches!'
  print m1.group(0)

if m2:
  print 'm2 matches!'
  print m2.group(0)

Explanation: The (? is the start of a "lookahead". This is a way to tell regex "at this point there should be something here that matches... 'this expression'. In this case, we follow it immediately with a !, i.e. (?! which signifies a "negative lookahead" - "not to be followed by 'this expression'". In this particular instance, I used with as the expression - space, followed by with. I could have chosen \s for "any whitespace" - but I figured you only used this as an example, and you could probably figure out the regex for "the thing that must not follow the thing I want".

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

Comments

0

I think you would like to use negative lookahead for this,

    r'.*rice(?! with).*' 

tested here

2 Comments

Note that the /regex/ notation is from perl. In python the / would be replaced with '.
you don't need the () around rice do you?

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.