正则表达式找到匹配的字符串,然后删除空格之间的所有内容

2024-05-29 06:39:39 发布

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

我对regex很陌生,所以我不知道该怎么做。仅供参考,我正在使用Python,但我不确定这有多重要。你知道吗

我想做的是这样的:

string1 = 'Metro boomin on production wow'
string2 = 'A loud boom idk why I chose this as an example'
pattern = 'boom'
result = re.sub(pattern, ' ____ ', string1)
result2 = re.sub(pattern, ' ____ ', string2)

现在那会给我"Metro ____in on production wow""a loud ____ idk why I chose this as an example

我想要的是"Metro ______ on production wow""a loud ____ idk why I chose this as an example"

基本上我想在另一个字符串中找到一个目标字符串,然后将匹配的字符串和2个空格之间的所有内容替换为一个新字符串

有办法吗?如果可能,最好根据原始字符串的长度在替换字符串中使用可变长度


Tags: 字符串anonexampleasthisproductionpattern
1条回答
网友
1楼 · 发布于 2024-05-29 06:39:39

你在正确的轨道上。只要扩展一下你的正则表达式。你知道吗

In [105]: string = 'Metro boomin on production wow'

In [106]: re.sub('boom[\S]*', ' ____ ', string)
Out[106]: 'Metro  ____  on production wow'

而且

In [137]: string2 = 'A loud boom'

In [140]: re.sub('boom[\S]*', ' ____', string2)
Out[140]: 'A loud  ____'

\S*符号匹配零个或多个非空格的元素。你知道吗

要用相同数量的下划线替换文本,请指定lambda回调,而不是替换字符串:

re.sub('boom[\S]*', lambda m: '_' * len(m.group(0)), string2)

相关问题 更多 >

    热门问题