Python 如何基于多个单词或子字符串拆分字符串
我想在python中基于多个单词拆分一个字符串,让我们有一个SQL查询Python 如何基于多个单词或子字符串拆分字符串,python,regex,string,Python,Regex,String,我想在python中基于多个单词拆分一个字符串,让我们有一个SQL查询 从表1中选择a1作为tb1,将表2作为tb1.a2=tb2.a2上的tb2,其中tb1.a3='something' 现在我想把这个字符串拆分成from,join,where,然后得到 { 选择a1, 表1为tb1, 表2为tb1.a2上的tb2=tb2.a2, tb1.a3=‘某物’ }有一个内置的库: import re result = re.split('from|join|where', yourStr) P
从表1中选择a1作为tb1,将表2作为tb1.a2=tb2.a2上的tb2,其中tb1.a3='something'
现在我想把这个字符串拆分成from
,join
,where
,然后得到
{
选择a1,
表1为tb1,
表2为tb1.a2上的tb2=tb2.a2,
tb1.a3=‘某物’
}
有一个内置的库:
import re
result = re.split('from|join|where', yourStr)
PS:@anubhava溶液更好,在拆分过程中为测定仪添加空白。您可以使用:
您可以在其中使用sqlparse.format()
格式化SQL查询,这将返回插入\n
字符的查询。然后,您可以在换行符上拆分以获得所需的列表
您可以使用pip install sqlparse
安装此模块 re.split(r'\s+(?:from | join | where)\s+',$str)
>>> 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'"]