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
2 Answers
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
Comments
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.
2 Comments
lmouhib
Thanks for your answer. But I omitted to say that I want to use the said operations in a lexer, so I don't know exactly when to split a string although the grammar is finite and unambiguous
Avinash Raj
what do you mean by said operations? is this won't satisfy your needs then provide an example along with expected output.
(.*?)yourpattern(.*)