【发布时间】: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