0

I'm trying to use the re module in a way that it will return bunch of characters until a particular string follows an individual character. The re documentation seems to indicate that I can use (?!...) to accomplish this. The example that I'm currently wrestling with:

str_to_search = 'abababsonab, etc'
first = re.search(r'(ab)+(?!son)', str_to_search)
second = re.search(r'.+(?!son)', str_to_search)

first.group() is 'abab', which is what I'm aiming for. However, second.group() returns the entire str_to_search string, despite the fact that I'm trying to make it stop at 'ababa', as the subsequent 'b' is immediately followed by 'son'. Where am I going wrong?

1
  • Are you trying to INCLUDE the full ababab prior to son or just the first abab stopping before abson? Commented Nov 7, 2013 at 19:32

3 Answers 3

2

It's not the simplest thing, but you can capture a repeating sequence of "a character not followed by 'son'". This repeated expression should be in a non-capturing group, (?: ... ), so it doesn't mess with your match results. (You'd end up with an extra match group)

Try this:

import re

str_to_search = 'abababsonab, etc'
second = re.search(r'(?:.(?!son))+', str_to_search)
print(second.group())

Output:

ababa

See it here: http://ideone.com/6DhLgN

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

Comments

1

This should work:

second = re.search(r'(.(?!son))+', str_to_search)
#output: 'ababa'

3 Comments

Not sure why you used .? and not .
This worked (and was the easiest for me to wrap my brain around). Thanks for the help everyone!
What @void has is a repeated capture group, which appears as match group 1, and overwrites itself each iteration of the +. That's why I added the ?: ... Just a warning to anyone who tries to understand what's going on exactly with this.
0

not sure what you are trying to do

  1. check out string.partition

  2. '.+?' is the minimal matcher, otherwise it is greedy and gets it all

  3. read the docs for group(...) and groups(..) especially when passing group number

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.