Как я могу заменить группу букв между символами, используя Python и регулярное выражение - PullRequest
1 голос
/ 30 сентября 2019

Я пытаюсь использовать Python и регулярные выражения для замены любого количества слов / пробелов в строке между двумя символами%% на '_____', чтобы создать пробел из строки, подобной этой:

input_string = "Нелегко найти% tailor% = (человек, который делает костюмы)" *

результирующий вывод должен выглядеть следующим образом ...

«Нелегко найти% _____% = (человека, который делает костюмы)»

Обратите внимание, мне нужен%, чтобы остаться

Ответы [ 5 ]

2 голосов
/ 30 сентября 2019

Вы можете использовать re.sub со следующим шаблоном:

import re
re.sub(r'(?<=%).*?(?=%)','_____', input_string)
# "it's not easy to find a %_____% =(person who makes suits)"
1 голос
/ 30 сентября 2019

Из примера видно, что вы хотите оставить пробел в начале и конце слова:

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

ВЫХОД:

it's not easy to find a % ____ % =(person who makes suits)
it's not easy to find a % ______________ % =(person who makes suits)
1 голос
/ 30 сентября 2019
**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)
1 голос
/ 30 сентября 2019

Вы можете попробовать с помощью регулярных выражений lookahead и lookbehind заменить текст между двумя % символами. re.sub() ваш друг здесь ?

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)

РАБОЧАЯ ДЕМО: https://rextester.com/NRHMW81828

0 голосов
/ 30 сентября 2019

Просто используйте 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)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...