python - Python 正则表达式以特殊格式的字符串命名组
问题描述
客观的:
- 我有输入字符串,它由逗号和键值分隔
- 我想用名称组编写正则表达式,以便我可以提取和替换每个属性的值
在字符串中*keyword , property1 = ABC, property2 = 2
我想查找和替换的值property1
和property2
名称
对于给定的字符串*keyword , property1 = ABC, property2 = 2
,结果字符串应该是*keyword , property1 = DEF, property2 = 10
请参阅下面的代码
import re
# find property1 in given string and replace its new value
property1 = 'DEF'
# find property2 in given string and replace its new value
property2 = '10'
line1 = '*keyword , property1 = ABC, property2 = 2 '
line2 = '*keyword , property2 = 2, property1 = ABC ' #property2 comes before proeprty1
line3 = '*keyword,property1=ABC,property2= 2' #same as line 1 but without spaces
regex_with_named_group = r'=\s*(.*)\s*,\s*property1=\s*(.*)\s*,'
line1_found = re.search(regex_with_named_group, line1)
line2_found = re.search(regex_with_named_group, line2)
line3_found = re.search(regex_with_named_group, line3)
if line1_found:
print( line1_found.group('property1'), line1_found.group('property2') )
if line2_found:
print( line2_found.group('property1'), line2_found.group('property2') )
if line3_found:
print(line3_found.group('property1'), line3_found.group('property2'))
解决方案
为了实现你的目标,我建议考虑使用re.sub函数。
import re
line0 = '*keyword , fruit=apple, juice= mango'
line1 = '*keyword , property1 = ABC, property2 = 2 '
line2 = '*keyword , property2 = 2, property1 = ABC ' #property2 comes before proeprty1
line3 = '*keyword,property1=ABC,property2= 2' #same as line 1 but without spaces
regex_with_named_group = re.compile(r'(?P<prop>\w+)(?P<map>\s*=\s*)(?P<val>\w+)')
repl = {'fruit':'avocado', 'property1':170}
for l in [line0, line1, line2, line3]:
s = regex_with_named_group.sub(lambda m: m.group('prop') + m.group('map') +
(str(repl[m.group('prop')])
if m.group('prop') in repl
else m.group('val')), l)
print(s)
结果:
*keyword , fruit=avocado, juice= mango
*keyword , property1 = 170, property2 = 2
*keyword , property2 = 2, property1 = 170
*keyword,property1=170,property2= 2
演示。
推荐阅读
- monitoring - 在 NiFi 中创建自定义 Prometheus 指标
- wpf - WPF 为我的面板中的所有 TabItems 显式使用样式
- javascript - 随机从数组中获取更大数字的算法
- javascript - JSON如何删除字符串的'字母
- python - 什么是上下文中的小数余数 Python 的除法总是返回一个浮点数?
- python - 在子图中绘制水平线
- android-studio - 颤振无法从.iml文件Android Studio加载设置
- sql - PIVOT 没有聚合转换 2X2 表
- ios - 处理应用内购买的消耗品退款通知
- java - 为什么 new 用来访问类的构造函数?