在Python中工作时,如何在正则表达式的结果中保留反斜杠?
我想要匹配的字符串包括一些转义序列,例如“It\'s Something”。与“.*?”匹配没有问题,但结果会自动转义。如何防止自动转义,并保持反斜杠原样?
例如:
>>> re.findall('\((?P<content>.*?)\)','(It\'s something)')
["It's something"]
我想要的是:
[r"It\'s something"]
The strings I want to match includes some escape sequences, like 'It\'s something'. It's no problem to match it with '.*?', however the result is escaped automatically. How to prevent the automatic escaping, and keep the backslashes as they are?
For example:
>>> re.findall('\((?P<content>.*?)\)','(It\'s something)')
["It's something"]
And what I want is:
[r"It\'s something"]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
输入字符串也必须是原始字符串。否则,它会在正则表达式看到它之前被转换:
The input string needs to be a raw string also. Otherwise, it is converted before the regex sees it:
您的输入字符串中没有反斜杠。
There is no backslash in your input string.