[英]Regex Replace Words Containing Specified Substring
我正在嘗試替換字符串中包含某個 substring 的單詞。 這是一個例子
import regex as re
given_in = 'My cat is not like other cats'
desired_out = 'My foo is not like other foo'
我努力了
print(re.sub('cat', 'foo', given_in))
>>>> 'My foo is not like other foos'
和
print(re.sub('.*cat.*', 'foo', given_in))
>>>> 'foo'
這里的正確方法是什么?
這將起作用:
import re
given_in = 'My cat is not like other cat'
desired_out = 'My foo is not like other foo'
out = re.subn("\w*(cat)\w*", "foo", given_in)
print(out)
output:
'My foo is not like other foo'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.