【问题标题】:Python regex named groups in special formated stringPython 正则表达式以特殊格式的字符串命名组
【发布时间】:2019-12-16 09:12:39
【问题描述】:

目标:

  1. 我有输入字符串,它由逗号和键值分隔
  2. 我想用名称组编写正则表达式,以便提取和替换每个属性的值

在字符串*keyword , property1 = ABC, property2 = 2 中,我想按名称查找和替换property1property2 的值

对于给定的字符串 *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'))

【问题讨论】:

  • 你想要什么输出格式
  • 我想将 property1 的值替换为 ABC ,例如使用命名组获取它
  • 除非我遗漏了什么,否则您的正则表达式似乎没有可以使用此构造创建的命名捕获组:(?P<name>...)
  • @SitiSchu 是的,我不熟悉命名组语法,需要在这里提出建议

标签: python regex regex-group


【解决方案1】:

为了实现你的目标,我建议考虑使用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

Demo.

【讨论】:

  • thankx,非常有帮助,但为了举例,我简化并编写了 proeprty1 和 proeprty2。它们实际上可以是 *keyword , fruit=apple, juice= mango 之类的任何东西
  • 谢谢。我想要什么!顺便说一句,我如何替换字符串中的新值?例如找到水果的价值并改变它
  • 我稍微重写了我的代码以使其符合您的要求。但是我仍然不明白如何处理“*关键字”部分。
  • 如何替换每个属性的值?
  • 就像d['fruit'] = 'avocado' 一样简单。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-28
  • 1970-01-01
  • 1970-01-01
  • 2014-04-28
  • 2018-06-13
  • 2023-03-31
相关资源
最近更新 更多