简体   繁体   English

带单词的 Python re.sub

[英]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]..... [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所以我需要删除完整的[Amazon & Wallmart](Amazon & Wallmart)如果亚马逊在里面

I tried that, but does not work我试过了,但不起作用

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

In Python, escape the backslashes or use the r prefix.在 Python 中,转义反斜杠或使用r前缀。

Using the former:使用前者:

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

Using the latter:使用后者:

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

In Regex, replace .*Amazon* with .*Amazon.* .在正则表达式中,将.*Amazon*替换为.*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.前者将匹配任何内容或任何内容,然后是Amazo后跟零个或多个n * s,而后者将匹配任何内容或任何内容,然后是Amazon后跟任何内容或任何内容。

Also, you can use the backreference feature for Regex.此外,您可以使用正则表达式的反向引用功能

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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