【问题标题】:How to use variable in python regex?如何在 python 正则表达式中使用变量?
【发布时间】:2015-02-08 09:28:27
【问题描述】:

我正在尝试处理来自变量的正则表达式中的用户输入。经过大量搜索,我想出了以下内容:

代码变量说明:

step 是用作正则表达式输入的字符串

例如

替换|-|空格,

替换|*|null,

替换|/|\|squot|空格

b is a list 个元素。根据正则表达式获取和修改元素。

i is integer 从其他函数接收到使用 i 作为索引访问列表 b

我处理上面的字符串得到数组,然后用数组的最后一个元素作为替换字符串

第一个元素被删除,因为它不是必需的。 所有其他元素都需要替换为替换字符串。

def replacer(step,i,b):
    steparray = step.split('|')
    del steparray[0]
    final = steparray.pop()

    if final == "space":
        subst = u" "
    elif final == "squot":
        subst = u"'"
    elif final == "dquot":
        subst = u"\""
    else:
        subst = u"%s"%final

    for input in xrange(0,len(steparray)):
        test=steparray[input]
        regex = re.compile(ur'%s'%test)
        b[i] = re.sub(regex, subst, b[i])
    print b[i]

但是,当我运行上面的代码时,会显示以下错误:

  File "CSV_process.py", line 78, in processor
    replacer(step,i,b)
  File "CSV_process.py", line 115, in replacer
    regex = re.compile(ur'%s'%test)
  File "/usr/lib/python2.7/re.py", line 190, in compile
    return _compile(pattern, flags)
  File "/usr/lib/python2.7/re.py", line 242, in _compile
    raise error, v # invalid expression
sre_constants.error: nothing to repeat

我尝试了很多,但不明白正则表达式的工作原理。请帮助解决错误。

最终要求是从用户输入中获取一个特殊字符并将其替换为另一个字符(同样来自用户输入)

PS:另外,代码没有 242 行,但错误在 242 行。错误是在 for 循环中数组结束后发生的吗?

【问题讨论】:

  • 可能test* 开头。
  • *开头是什么意思?我不允许 * 作为输入,但 b[i] 可能包含 *

标签: python regex string variables


【解决方案1】:

* 这样的特殊字符应该转义以匹配字面意思。

>>> import re
>>> re.compile('*')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python27\lib\re.py", line 194, in compile
    return _compile(pattern, flags)
  File "C:\Python27\lib\re.py", line 251, in _compile
    raise error, v # invalid expression
sre_constants.error: nothing to repeat

使用re.escape,您可以逃脱它们:

>>> print(re.escape('*'))
\*
>>> re.compile(re.escape('*'))
<_sre.SRE_Pattern object at 0x000000000273DF10>

顺便说一句,如果您想简单地替换它们,则不需要正则表达式。为什么不用str.replace

replaced_string = string_object.replace(old, new)

【讨论】:

  • str.replace 会替换所有出现的特定字符吗?对不起,愚蠢的问题,刚开始用python编码。
  • @AJINKYA,是的。您可以控制将发生多少替换。试试'123123'.replace('2', '.')'123123'.replace('2', '.', 1)
猜你喜欢
  • 2017-10-11
  • 2019-11-08
相关资源
最近更新 更多