简体   繁体   中英

Python re.sub with word

i have problem!

I get automatically strings (titles) with sometimes like Amazon in it. But these are most times Like that

..... (Amazon & Wallmart) 

or ..... [Amazon & Wallmart]

But i want no to delete the hole () or [] and not just the Amazon in it.

So i need to delete the complete [Amazon & Wallmart] or (Amazon & Wallmart) if Amazon is in it

I tried that, but does not work

name = re.sub("[\(\[].*Amazon*?[\)\]]", "", name)

In Python, escape the backslashes or use the r prefix.

Using the former:

re.sub("[\\(\\[].*Amazon*?[\\)\\]]", "", name)

Using the latter:

re.sub(r"[\(\[].*Amazon*?[\)\]]", "", name)

In Regex, replace .*Amazon* with .*Amazon.* . The former will match anything or nothing followed by Amazo followed by zero or more n *s, while the latter will match anything or nothing followed by Amazon followed by anything or nothing.

Also, you can use the backreference feature for Regex.

re.sub(r"([\(\[]).*Amazon.*?\1", "", name)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM