如何在Python中使用re模块删除()
我在处理 XML 文本时遇到了麻烦。 我想从我的文本中删除 (),如下所示:
从 (apa-bhari(n))
到 apa-bhari(n )
编写了以下代码
name= re.sub('<b>\((.+)\)</b>','<b>\1</b>',name)
但这只能返回
<b></b>
我不理解转义序列和反向引用。请告诉我解决方案。
I am in trouble for processing XML text.
I want to delete () from my text as follows:
from <b>(apa-bhari(n))</b>
to <b>apa-bhari(n)</b>
The following code was made
name= re.sub('<b>\((.+)\)</b>','<b>\1</b>',name)
But this can only returns
<b></b>
I do not understand escape sequences and backreference. Please tell me the solution.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要使用原始字符串 ,或转义斜杠:
You need to use raw strings, or escape the slashes:
Python 字符串中如果后跟数字,则需要转义反斜杠;以下表达式全部为真:
因此,您的代码将是
或者,使用正则表达式字符串定义:
You need to escape backslashes in Python strings if followed by a number; the following expressions are all true:
So, your code would be
Alternatively, use the regular expression string definition:
尝试:
或者,如果您不想在使用反斜杠的任何地方都出现带有
\\
的不可读代码,请不要手动转义反斜杠,而是在字符串之前添加r
,例如:r"myString\"
与"myString\\"
相同。Try:
or if you do not want to have an illisible code with
\\
everywhere you are using backslashes, do not escape manually backslashes, but add anr
before the string, ex:r"myString\"
is the same as"myString\\"
.