John Aiton
John Aiton

Reputation: 85

How can I replace a group of letters between to symbols using Python and regex

I'm trying to use Python and regex to replace any number of words / spaces in a string between two % % symbols with '_____' to create a gapfill from a string like this one:

input_string = "it's not easy to find a % tailor % =(person who makes suits)"

the resulting output should look like this...

"it's not easy to find a % _____ % =(person who makes suits)"

Note, I need the % to remain

Upvotes: 1

Views: 81

Answers (5)

A l w a y s S u n n y
A l w a y s S u n n y

Reputation: 38532

You can try with regex lookahead and lookbehind to replace the text between two % characters. re.sub() is your friend here 📍

import re

regex = r"(?<=%)([a-zA-Z0-9\s]+)(?=%)"

test_str = "it's not easy to find a % tailor % =(person who makes suits)"

subst = "_____"

# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 0, re.MULTILINE)

if result:
    print (result)

WORKING DEMO: https://rextester.com/NRHMW81828

Upvotes: 1

Charif DZ
Charif DZ

Reputation: 14741

From the example I can see that you want to keep space at the beginning and end of word:

import re
input_string = "it's not easy to find a % verylongtailor % =(person who makes suits)"
print(re.sub(r'(?<=%)(\s*)(.+?)(\s*)(?=%)', r'\1____\3', input_string))

# if you want to keep the same length of the word
print(re.sub(r'(?<=%)(\s*)(.+?)(\s*)(?=%)', lambda m: '{}{}{}'.format(m.group(1), '_' * len(m.group(2)), m.group(3)), input_string))

OUTPUT:

it's not easy to find a % ____ % =(person who makes suits)
it's not easy to find a % ______________ % =(person who makes suits)

Upvotes: 1

M.achaibou
M.achaibou

Reputation: 101

**Juste Use :**
import re
input_string = "it's not easy to find a % tailor % =(person who makes suits)"
input_replace = re.sub('(?<=%).*?(?=%)', "'____'", input_string)
print(input_replace)

**OutPut:**
it's not easy to find a %'____'% =(person who makes suits)

Upvotes: 1

Fabio Caccamo
Fabio Caccamo

Reputation: 1971

Just use re.sub:

import re

input_str = "it's not easy to find a % _____ % = (person who makes a % _____ % suits)"
placeholder_re = r'\%([^\%]+)\%'
replacement_str = 'lorem ipsum'
output_str = re.sub(placeholder_re, replacement_str, input_str)
print(output_str)

Upvotes: 0

yatu
yatu

Reputation: 88276

You can use re.sub with the following pattern:

import re
re.sub(r'(?<=%).*?(?=%)','_____', input_string)
# "it's not easy to find a %_____% =(person who makes suits)"

Upvotes: 2

Related Questions