Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/309.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ajax/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何基于多个单词或子字符串拆分字符串_Python_Regex_String - Fatal编程技术网

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

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

我想在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)
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'"]