Python regular expression question - sub string but not prepended with
:)
I'm trying to sub foo to bar, but开发者_运维问答 only if it's not prepended with ie. /. So...
foobar should change to barbar, but /foobar not.
I've tried to add [^/] at beginning of my re, but that doesn't work if foo is at beginning of string.
I hate regular expressions! :P
Use a negative lookbehind assertion.
>>> re.search('(?<!/)foo', 'foo')
<_sre.SRE_Match object at 0x7f44891518b8>
>>> re.search('(?<!/)foo', '/foo')
>>> re.search('(?<!/)foo', 'barfoo')
<_sre.SRE_Match object at 0x7f4489151850>
try using \bfoo\b
\b is a word boundary, it deals with a lot of common cases like beginning of line, whitespace, etc.
精彩评论