1

I have something like this:

text = "hey;)there"

Need this:

text = "hey ;) there"

I am doing 2 passes:

op_1 = re.sub(r'([a-zA-Z])([:;()])', r'\1 \2', text)
final_result = re.sub(r'([:;()])([a-zA-Z])', r'\1 \2', op_1)

I am sure there must be an efficient way for this.

9
  • 1
    Could you be more explicit about the cases you do and don't want to handle? What's the actual task here? Commented Jun 24, 2016 at 10:44
  • just want to separate a few characters that don't match '\w', say for emoticons Commented Jun 24, 2016 at 10:48
  • In that case, would r'(\W{2,})' do it? Then you can just replace it with r' \1 ' - regex101.com/r/kM4qZ9/1 Commented Jun 24, 2016 at 10:48
  • @jonrsharpe gives me this ''hi \x01 there'' :) Commented Jun 24, 2016 at 10:51
  • 1
    Note the regex should be {2} for "precisely two" or {2,} for "at least two". :, - and ) are all matched by \W. Commented Jun 24, 2016 at 13:19

1 Answer 1

1

You can use lookaheads and lookbehinds with alternation

>>> re.sub('(?<=[a-zA-Z])(?=[:;()])|(?<=[:;()])(?=[a-zA-Z])', ' ', text)
'hey ;) there'

Regex Breakdown

(?<=[a-zA-Z]) #Lookbehind to match an alphabet
(?=[:;()]) #Lookahead to match the position of signs
| Alternation(OR)
(?<=[:;()]) #Lookbehind to match the position of signs
(?=[a-zA-Z]) #Lookahead to match an alphabet
Sign up to request clarification or add additional context in comments.

8 Comments

the result is not the same. :) a couple of characters are missing. I just want to separate the pattern.
Note that you can include explanations inline if you use triple-quoted r"""raw strings""" and the re.VERBOSE flag, often handy for keeping the information with the code.
@Kevad what characters are missing?
I need 'hey ;) there', the above snippet gives 'he ;) here'
@Kevad as you wish..you can use \W{2} for non-word character..feel free to give an upvote..:)
|

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.