如何使用 Python 和正则表达式替换符号之间的一组字母



我正在尝试使用 Python 和正则表达式将字符串中两个 % % 符号之间的任意数量的单词/空格替换为"_____"以从这样的字符串创建间隙填充:

input_string ="找到 % 裁缝 % =(制作西装的人(并不容易">

结果输出应如下所示...

"要找到一个%_____%=(制作西装的人(并不容易">

注意,我需要保留 %

您可以将re.sub与以下模式一起使用:

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

从示例中我可以看到您希望在单词的开头和结尾保留空格:

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)

您可以尝试使用正则表达式lookaheadlookbehind来替换两个%字符之间的文本。re.sub()是你的朋友 📍

import re
regex = r"(?<=%)([a-zA-Z0-9s]+)(?=%)"
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

只需使用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)

最新更新