python中的字符串解析/替换(使用reg表达式)

时间:2017-02-17 15:11:52

标签: python regex string parsing

我正在尝试编写解析器:将字符串转换为查询格式。并停留在字符串替换的特定点(通过匹配模式)。

我无法找出正则表达式模式匹配。

我有一个像

这样的input_string
spring.jpa.open-in-view=false

请帮助形成逻辑。

或者什么是reg模式(如果&或用单引号括起来与其他字符一起使用,不要替换,否则替换)?

2 个答案:

答案 0 :(得分:0)

它以某种奇怪的方式工作(可能不是pythonic),但它有效。

def rplc_str(s):
   sp = s.split("'")
   print('After split==',sp)
   sp1 = [x.replace(' & ', ' AND ') if ((x.startswith(' &')) or (x.startswith('] &'))) else x for x in sp]
   print('After replacing & ==',sp1)
   sp2 = [x.replace(' in ', ' IN ') if x.endswith(' [') else x for x in sp1]
   print('After replacing in ==',sp1)
   return "'".join(sp2)

ip_str = "CITY == 'Mumbai' & LOCATION in ['Harrys Bar & Cafe: Mumbai','Hard Rock Cafe in Mumbai']"
op_str = rplc_str(ip_str)
print(op_str)
#After split== ['CITY == ', 'Mumbai', ' & LOCATION in [', 'Harrys Bar & Cafe: Mumbai', ',', 'Hard Rock Cafe in Mumbai', ']']
#After replace & == ['CITY == ', 'Mumbai', ' AND LOCATION in [', 'Harrys Bar & Cafe: Mumbai', ',', 'Hard Rock Cafe in Mumbai', ']']
#After replace in == ['CITY == ', 'Mumbai', ' AND LOCATION in [', 'Harrys Bar & Cafe: Mumbai', ',', 'Hard Rock Cafe in Mumbai', ']']
#CITY == 'Mumbai' AND LOCATION IN ['Harrys Bar & Cafe: Mumbai','Hard Rock Cafe in Mumbai']

希望它有所帮助,但仍在等待一些pythonic答案(我的意思是reg expr。)

答案 1 :(得分:0)

使用re.sub()函数的简短解决方案:

import re

ip_query_string = "CITY == 'Mumbai' & LOCATION in ['Harrys Bar & Cafe: Mumbai','Hard Rock Cafe in Mumbai']"
op_query_string  = re.sub(r'^([^[]+?)(in)', r'\1IN', re.sub(r'^([^[]+?)(&)', r'\1AND', ip_query_string))

print(op_query_string)

输出:

CITY == 'Mumbai' AND LOCATION IN ['Harrys Bar & Cafe: Mumbai','Hard Rock Cafe in Mumbai']