如何在 python 正则表达式中使用变量?

How to use variable in python regex?

我正在尝试从变量处理正则表达式中的用户输入。经过大量搜索,我得出以下结论:

代码变量说明:

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

例如

替换|-|space,

替换|*|null,

替换|/|\|squot|space

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

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

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

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

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循环数组结束后出现的吗?

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

>>> 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)