Reputation: 47
Perl uses $` to return everything before the matched string and $' to return everything after the matched string. I was wondering if there is something similar in python or any work around to get it. Thanks
Upvotes: 0
Views: 315
Reputation: 126722
If you collect a MatchObject
from the result of a search
operation, you can use its contents to build the equivalent substrings to Perl's $`
and $'
Like this
import re
ss = '123/abc'
match = re.search('/', ss)
print ss[:match.start()]
print match.group()
print ss[match.end():]
output
123
/
abc
Upvotes: 1
Reputation: 174706
Just use re.split
command to split the input according to a particular regex and then get the string before the match from index 0 of returned list and the string after the match from index 1.
>>> word = 'foo'
>>> re.split(re.escape(word), 'barfoobuz', maxsplit=1)
['bar', 'buz']
By adding maxsplit=1
parameter, the above re.split
function will do splitting only one time according to the characters which matches the given pattern.
Upvotes: 1