【问题标题】:Python re regex sub letters not surrounded in quotes and not if they match specific word including regex group / matchPython re 正则表达式子字母不被引号括起来,如果它们匹配特定单词,包括正则表达式组/匹配,则不
【发布时间】:2023-03-09 22:03:01
【问题描述】:

如果它们将单词TODAY 与其中一部分包含匹配组的特定字符串匹配,则我需要子字母不被引号括起来,例如

import re
import string

s = 'AB+B+" HELLO"+TODAY()/C* 100'
x = re.sub(r'\"[^"]*\"|\bTODAY\b|([A-Z]+)', r'a2num("\g<0>")', s)

print (x)

预期输出:

'a2num("AB")+a2num("B")+" HELLO"+TODAY()/a2num("C")* 100'

实际输出:

'a2num("AB")+a2num("B")+a2num("" HELLO"")+a2num("TODAY")()/a2num("C")* 100'

我快到了,但它不遵守引号规则或TODAY 字规则,我知道字符串没有任何意义,但这只是对正则表达式的严格测试

【问题讨论】:

  • 只需要匹配大写字母?
  • @00 是的,整个字符串在手之前都是大写的

标签: python regex re


【解决方案1】:

您的正则表达式方法是正确的,但您需要在 re.sub 中使用 lambda 函数

>>> s = 'AB+B+" HELLO"+TODAY()/C* 100'
>>> rs = re.sub(r'"[^"]*"|\bTODAY\b|\b([A-Z]+)\b',
...     lambda m: 'a2num("' + m.group(1) + '")' if m.group(1) else m.group(), s)
>>> print (rs)

a2num("AB")+a2num("B")+" HELLO"+TODAY()/a2num("C")* 100

Code Demo

【讨论】:

    猜你喜欢
    • 2010-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-28
    • 1970-01-01
    • 2011-08-03
    相关资源
    最近更新 更多