我需要一些关于python中字符正则表达式问题的帮助。在
“是这个词的正确形式,但是在一篇文章中我找到了“我应该用什么正则表达式来代替字符。”。在
import re
name = "拉柏多公园"
line = "whatever whatever it is then there comes a 拉柏 多公 园 sort of thing"
line2 = "whatever whatever it is then there comes another拉柏 多公 园 sort of thing"
line3 = "whatever whatever it is then there comes yet another 拉柏 多公 园sort of thing"
line4 = "whatever whatever it is then there comes a拉柏 多公 园sort of thing"
firstchar = "拉"
lastchar = "园"
我需要替换行中的字符串,以便输出行看起来像这样
^{pr2}$我尝试过这些,但是regex的结构很糟糕:
reline = line.replace (r"firstchar*lastchar", name) #
reline2 = reline.replace (" ", " ")
print reline2
有人能帮我纠正我的正则表达式吗?在
谢谢
(我假设您使用的是python3,因为您在常规字符串中使用unicode字符。对于python2,在每个字符串文本之前添加
u
。)Python3
所以可以用
^{pr2}$Python2
所以可以用
讨论
结果将被空格包围。更一般地说,如果您希望它在行的开始或结尾,或者在逗号或句点之前工作,您必须用更复杂的东西来替换
' ' + name + ' '
。在编辑:固定。当然,您必须使用
re
库函数。在相关问题 更多 >
编程相关推荐