替换python中具有动态字符的字符串

2024-09-28 01:24:05 发布

您现在位置:Python中文网/ 问答频道 /正文

试图用正则表达式替换字符串,但未能成功。你知道吗

字符串是“LIVE\u CUS2\u PHLR182”、“LIVE\u CUS2ee\u phl182”和“phl182-测试恢复”。这里我需要将phl182作为所有字符串的输出,但第二个字符串的“ee”不是常量。它可以是带2的字符串或数字字符。在下面这是我试过的密码。你知道吗

对于第一个和最后一个字符串,我只是简单地使用了replace函数,如下所示。你知道吗

s = "LIVE_CUS2_PHLR182"
s.replace("LIVE_CUS2_", ""), s.replace(" - testing recovery","")
>>> PHLR182

但有一秒钟我试着像下面这样。你知道吗

1. s= "LIVE_CUS2ee_PHLR182"
   s.replace(r'LIVE_CUS2(\w+)*_','')

2. batRegex = re.compile(r'LIVE_CUS2(\w+)*_PHLR182')
   mo2 = batRegex.search('LIVE_CUS2dd_PHLR182')
   mo2.group()

3. re.sub(r'LIVE_CUS2(?is)/s+_PHLR182', '', r)

在所有情况下,我都无法获得“PHLR182”作为输出。请帮帮我。你知道吗


Tags: 字符串relive数字字符replaceee常量
1条回答
网友
1楼 · 发布于 2024-09-28 01:24:05

我想这就是你需要的:

import re

texts = """LIVE_CUS2_PHLR182
LIVE_CUS2ee_PHLR182
PHLR182 - testing recovery""".split('\n')

pat = re.compile(r'(LIVE_CUS2\w{,2}_| - testing recovery)')
#                   1st alt pattern | 2nd alt pattern
#                   Look for 'LIV_CUS2_' with up to two alphanumeric characters after 2
#                               ... or Look for ' - testing recovery'

results = [pat.sub('', text) for text in texts]
# replace the matched pattern with empty string

print(f'Original: {texts}')
print(f'Results: {results}')

结果:

Original: ['LIVE_CUS2_PHLR182', 'LIVE_CUS2ee_PHLR182', 'PHLR182 - testing recovery']
Results: ['PHLR182', 'PHLR182', 'PHLR182']

Python演示:https://repl.it/repls/ViolentThirdAutomaticvectorization

正则表达式演示:https://regex101.com/r/JiEVqn/2

相关问题 更多 >

    热门问题