正则替换合理间隔

2024-10-06 07:37:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要一些关于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

有人能帮我纠正我的正则表达式吗?在

谢谢


Tags: ofnameislineanotheritsort字符
1条回答
网友
1楼 · 发布于 2024-10-06 07:37:17

(我假设您使用的是python3,因为您在常规字符串中使用unicode字符。对于python2,在每个字符串文本之前添加u。)

Python3

import re

name = "拉柏多公园"
# the string of Chinese characters, with any number of spaces interspersed.
# The regex will match any surrounding spaces.
regex = r"\s*拉\s*柏\s*多\s*公\s*园\s*"

所以可以用

^{pr2}$

Python2

# -*- coding: utf-8 -*-

import re

name = u"拉柏多公园"
# the string of Chinese characters, with any number of spaces interspersed.
# The regex will match any surrounding spaces.
regex = ur"\s*拉\s*柏\s*多\s*公\s*园\s*"

所以可以用

reline = re.sub(regex, u' ' + name + u' ', line)

讨论

结果将被空格包围。更一般地说,如果您希望它在行的开始或结尾,或者在逗号或句点之前工作,您必须用更复杂的东西来替换' ' + name + ' '。在

编辑:固定。当然,您必须使用re库函数。在

相关问题 更多 >