34

I have a text file and every time that the word "get" occurs, I need to insert an @ sign after it.

How do I add a character after a specific word using regex?

3
  • 1
    do you want to add an @ after midget ? Commented Dec 23, 2013 at 0:07
  • 1
    I do not want to add after midget. Does that change the regex? Commented Dec 23, 2013 at 0:11
  • 1
    Yes, a little. Martijn Pieters has the good answer. You only need to add word boundaries before and after the word "get" in the pattern: \bget\b Commented Dec 23, 2013 at 0:13

3 Answers 3

56

Use re.sub() to provide replacements, using a backreference to re-use matched text:

import re

text = re.sub(r'(get)', r'\1@', text)

The (..) parenthesis mark a group, which \1 refers to when specifying a replacement. So get is replaced by get@.

Demo:

>>> import re
>>> text = 'Do you get it yet?'
>>> re.sub(r'(get)', r'\1@', text)
'Do you get@ it yet?'

The pattern will match get anywhere in the string; if you need to limit it to whole words, add \b anchors:

text = re.sub(r'(\bget\b)', r'\1@', text)
Sign up to request clarification or add additional context in comments.

3 Comments

♦: How to pass get in a variable? I mean how to set pass_variable_dynamically = "get" #may be some other string re.sub(r'pass_variable_dynamically', r'\1@', text)) not working
@RasmiRanjanNayak: you mean you want to parameterise the regex? Escape your variable with re.escape() and use normal string interpolation techniques: re.sub(r'(\b{}\b)'.format(variable), r'\1@', text) would use variable to obtain the word to replace.
With f-strings, it will be re.sub(rf'(\b{variable}\b), r'\1@', text)
2

You can replace (zero-width) matches of (?<=\bget\b) with '@'.

import re
text = re.sub(r'(?<=\bget\b)', '@', text)

Demo

(?<=\bget\b) is a positive lookbehind. It asserts that the (zero-width) match is immediately preceded by 'get'. The word boundaries \b are added to prevent matching that string when it is immediately preceded and/or followed by a word character (such as 'budget', 'getting' or 'nuggets').

Comments

1

To insert a character after every occurrence of a string ('get'), you don’t even need regex. Split on 'get' and concatenate with '@get' in between strings.

text = 'Do you get it yet?'
'get@'.join(text.split('get'))            # 'Do you get@ it yet?'

However, if 'get' has to be an entire word, re.split() could be used instead.

text = 'Did you get it or forget?'
'get@'.join(re.split(r"\bget\b", text))   # 'Did you get@ it or forget?'

2 Comments

I don't see how joining re.split results is any simpler than using re.sub.
@KarlKnechtel I meant str.split was simpler. I agree, re.split is not simpler.

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.