如何基于多个单词或子字符串拆分字符串

问题描述 投票:-1回答:2

我想基于多个单词在python中拆分一个字符串,让我们有一个SQL查询

select a1 from table1 as tb1 join table2 as tb2 on tb1.a2 = tb2.a2 where tb1.a3 = 'something'

现在我想一次性拆分fromjoinwhere这个字符串,想得到一份 { select a1, table1 as tb1, table2 as tb2 on tb1.a2 = tb2.a2, tb1.a3 = 'something' }列表

python regex string
2个回答
2
投票

有一个内置的库:

import re

result = re.split('from|join|where', yourStr)

PS:@anubhava解决方案更好,其中包括拆分期间确定器的空格。


1
投票

你可以使用sqlparse

>>> import sqlparse
>>> sql = "select a1 from table1 as tb1 join table2 as tb2 on tb1.a2 = tb2.a2 wher
e tb1.a3 = 'something'"
>>> formatted_sql = sqlparse.format(sql, reindent=True, keyword_case='lower')
>>> formatted_sql
"select a1\nfrom table1 as tb1\njoin table2 as tb2 on tb1.a2 = tb2.a2\nwhere tb1.a3 = 'something'"
>>> formatted_sql.split('\n')
['select a1', 'from table1 as tb1', 'join table2 as tb2 on tb1.a2 = tb2.a2', "where tb1.a3 = 'something'"]

在哪里可以使用sqlparse.format()格式化SQL查询,这会使用插入的\n字符返回您的查询。然后,您可以拆分换行符以获得所需的列表。

您可以使用pip install sqlparse安装此模块。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.