簡體   English   中英

正則表達式查找匹配的字符串,然后刪除空格之間的所有內容

[英]Regular expression find matching string then delete everything between spaces

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個空格之間的所有內容替換為一個新字符串

有辦法嗎? 另外,如果可能的話,最好在替換字符串中根據原始字符串的長度設置可變的長度

您走在正確的軌道上。 只需稍微擴展一下正則表達式即可。

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM