简体   繁体   中英

split string based on regular expression value in python

suppose i have a string

exp = '"security_datafilter"."PRODUCT_CATEGORIES"."CATEGORY_NAME" IN ("CPU","Storage")' 

I want to split the string based on word IN so my exprected result is

['"security_datafilter"."PRODUCT_CATEGORIES"."CATEGORY_NAME"','IN','("CPU","Storage")']

but in my case it doesnt work This is what i have tried

import re
exp_split = re.split(r'( in )',exp,re.I) 

re documentation : re.split(pattern, string, maxsplit=0, flags=0)

The split() function expects that the third positional argument is the maxsplit argument. Your code gives re.I to maxsplit and no flags . You should give flags as a keyword argument like so:

exp_split = re.split(r'( in )',exp, flags=re.I)

its simply necessary to capitalize your delimiter and if you dont want the spaces in your result keep them outside your capturing group:

exp_split = re.split(r'\s(IN)\s', exp, re.I) 
exp_split

Output

['"security_datafilter"."PRODUCT_CATEGORIES"."CATEGORY_NAME"', 'IN', '("CPU","Storage")']

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