【发布时间】:2017-02-17 15:11:51
【问题描述】:
我正在尝试编写解析器:将字符串转换为查询格式。并停留在字符串替换的特定点(通过匹配模式)。
我无法弄清楚正则表达式模式匹配。
我有一个像
这样的 input_stringip_query_string = "CITY == 'Mumbai' & LOCATION in ['Harrys Bar & Cafe: Mumbai','Hard Rock Cafe in Mumbai']"
#Mark the """& after CITY == """ and """ in after LOCATION""".
#Then there is another "& and a string ' in '" inside values for in-condition.
#My output should be:
op_query_string = "CITY == 'Mumbai' AND LOCATION IN ['Harrys Bar & Cafe: Mumbai','Hard Rock Cafe in Mumbai']"
#if i will find ' & ' or a ' in ' (before and after there are spaces):: I have to replace them with ' AND ' and ' IN ' respectively.(In this case a ip_string.replace(' & ', ' AND ').replace(' in ', ' In ')) would work.BUT read next point.
#And if they are inside a in-condition values like 'Harrys Bar & Cafe: Mumbai','Hard Rock Cafe in Mumbai' then don't replace them. keep them as is.
#If you look at op_string in-condition, the & and in are not replaced.
请帮助形成一个逻辑。
或者什么是 reg 模式(如果 & 或与其他字符一起用单引号括起来,不要替换,否则替换)?
【问题讨论】:
-
为什么
'Harry's应该变成'Harrys? -
对不起,有一个错字,一直是哈利。编辑了问题。
标签: python regex string parsing