0

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

1
  • The work around is to split the string with your pattern, but if you hope to use the parts for a replacement string you can't do that. you can use capturing groups instead: (.*?)yourpattern(.*) Commented Apr 6, 2015 at 23:26

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

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
what do you mean by said operations? is this won't satisfy your needs then provide an example along with expected output.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.