简体   繁体   English

根据 python 中的正则表达式值拆分字符串

[英]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我想根据单词IN拆分字符串,所以我的预期结果是

['"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)重新文档re.split(pattern, string, maxsplit=0, flags=0)

The split() function expects that the third positional argument is the maxsplit argument. split() function 期望第三个位置参数是maxsplit参数。 Your code gives re.I to maxsplit and no flags .您的代码将re.I提供给maxsplit并且没有flags You should give flags as a keyword argument like so:您应该将flags作为关键字参数提供,如下所示:

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 Output

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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