Search code examples
pythonregexlookbehind

python regex with conditional lookbehind


I'm looking for substring starting with @ and ending with the first \s occurrence. It's necessary to have @ at the beginning of the string or after space.

Example: @one bla bla bla @two @three@four #@five

Result: @one, @two, @three@four

I end up with this re: ((?<=\s)|(?<=^))@[^\s]+ which works fine in sublime text 2, but returns empty strings in python.

python code:

re.findall(r'((?<=^)|(?<=\s))@[^\s]+', '@one bla bla bla @two @three@four #@five')

Solution

  • Your capturing group isn't capturing the text that you are really looking for:

    (?:(?<=^)|(?<=\s))(@[^\s]+)
    

    Now, it works:

    >>> re.findall(r'(?:(?<=^)|(?<=\s))(@[^\s]+)', '@one bla bla bla @two @three@four #@five')
    ['@one', '@two', '@three@four']