Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining the unmatched portion of a string using a regex in Python

Tags:

python

regex

Suppose I have a string "a foobar" and I use "^a\s*" to match "a ".

Is there a way to easily get "foobar" returned? (What was NOT matched)

I want to use a regex to look for a command word and also use the regex to remove the command word from the string.

I know how to do this using something like:

mystring[:regexobj.start()] + email[regexobj.end():]

But this falls apart if I have multiple matches.

Thanks!

like image 974
Art Avatar asked Feb 03 '10 20:02

Art


4 Answers

Use re.sub:

import re
s = "87 foo 87 bar"
r = re.compile(r"87\s*")
s = r.sub('', s)
print s

Result:

foo bar
like image 169
Mark Byers Avatar answered Sep 20 '22 11:09

Mark Byers


from http://docs.python.org/library/re.html#re.split

>>> re.split('(\W+)', 'Words, words, words.')
['Words', ', ', 'words', ', ', 'words', '.', '']

so your example would be

>>> re.split(r'(^a\s*)', "a foobar")
['', 'a ', 'foobar']

at which point you can separate the odd items (your match) from the even items (the rest).

>>> l = re.split(r'(^a\s*)', "a foobar")
>>> l[1::2] # matching strings
['a ']
>>> l[::2] # non-matching strings
['', 'foobar']

This has the advantage over re.sub in that you can tell, when, where, and how many matches were found.

like image 32
cobbal Avatar answered Sep 19 '22 11:09

cobbal


>>> import re
>>> re.sub("87\s*", "", "87 foo 87 bar")
'foo bar'
like image 21
Greg Bacon Avatar answered Sep 20 '22 11:09

Greg Bacon


Instead of splitting or separating, maybe you can use re.sub and substitute a blank, empty string ("") whenever you find the pattern. For example...

>>> import re
>>> re.sub("^a\s*", "","a foobar")
'foobar''
>>> re.sub("a\s*", "","a foobar a foobar")
'foobr foobr'
>>> re.sub("87\s*", "","87 foo 87 bar")
'foo bar'
like image 40
VMDX Avatar answered Sep 20 '22 11:09

VMDX