简体   繁体   中英

how to use regex in python to split a string by ","

Here is sql string, and I want to split it by ",", but not the "," in datatime. For example, if the string is:

sub_sql = """(14,datetime.datetime(2013, 7, 22, 10, 40, 22),NULL,'Logical reads','50','ratio','y','Oracle','recommand')"""

and the result is expected as a list: [14, "datetime.datetime(2013 7, 22, 10, 40, 22)", "NULL", 'Logical reads", "50", "ratio", "y", "Oracle", "recommand"]

how to do it with a simple way in python regex?

If you can ensure the commas in the datatime is followed by one space, and there is no space after the other commas, then the following regex will work:

import re
sub_sql = """(14,datetime.datetime(2013, 7, 22, 10, 40, 22),NULL,'Logical reads','50','ratio','y','Oracle','recommand')"""
sub_sql = sub_sql[1:-1] #remove the first and last bracket
re.split(",(?! )", sub_sql)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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