English Grad
English Grad

Reputation: 1395

Adding characters after a certain word in Python using regex

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?

Upvotes: 34

Views: 37342

Answers (3)

Martijn Pieters
Martijn Pieters

Reputation: 1123410

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)

Upvotes: 56

Cary Swoveland
Cary Swoveland

Reputation: 110725

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').

Upvotes: 2

cottontail
cottontail

Reputation: 23271

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?'

Upvotes: 1

Related Questions