如何使用Python删除特定单词之前的所有单词(如果有多个特定单词)?

eli*_*isa 2 python regex postgresql python-3.x

我想删除特定单词之前的所有单词。但我的句子里有一些特定的词。下面的例子:

dvdrentalLOG: statement: SELECT email, actor.last_name, count(actor.last_name) FROM (SELECT email, actor_id FROM (SELECT email, film_id FROM (SELECT email, inventory_id FROM customer as cu JOIN rental ON cu.customer_id = rental.customer_id ORDER BY email) as sq JOIN inventory ON sq.inventory_id = inventory.inventory_id) as sq2 JOIN film_actor ON sq2.film_id = film_actor.film_id) as sq3 JOIN actor ON sq3.actor_id = actor.actor_id GROUP BY email, actor.last_name ORDER BY COUNT(actor.last_name) DESC
Run Code Online (Sandbox Code Playgroud)

在上面的示例中,我想删除第一个SELECT之前的所有单词。我已经尝试过如何删除Python中特定字符之前的所有字符?

知道我需要做什么吗?

Swe*_*per 5

您可以使用此正则表达式并替换为空字符串:

^.+?(?=SELECT)
Run Code Online (Sandbox Code Playgroud)

像这样:

result = re.sub(r"^.+?(?=SELECT)", "", your_string)
Run Code Online (Sandbox Code Playgroud)

解释:

因为您想要删除第一个之前的所有内容SELECT,所以匹配将从字符串的开头开始^。然后你懒惰地匹配任何字符.+?,直到你看到SELECT

或者,删除前瞻并替换为SELECT

result = re.sub(r"^.+?SELECT", "SELECT", your_string)
Run Code Online (Sandbox Code Playgroud)

编辑:

我找到了另一种方法来做到这一点partition

partitions = your_string.partition("SELECT")
result = partitions[1] + partitions[2]
Run Code Online (Sandbox Code Playgroud)