在问这个问题时,我意识到我对原始字符串知之甚少.对于那些自称是Django训练师的人来说,这很糟糕.
我知道编码是什么,而且我知道u''自从我得到什么是Unicode以来我们独自做了什么.
但到底r''做了什么呢?它会产生什么样的字符串?
And above all, what the heck does ur'' do?
Finally, is there any reliable way to go back from a Unicode string to a simple raw string?
Ah, and by the way, if your system and your text editor charset are set to UTF-8, does u'' actually do anything?
我想使用来自用户的输入作为搜索某些文本的正则表达式模式.它有效,但我如何处理用户放置在正则表达式中有意义的字符的情况?例如,用户想要搜索Word (s):正则表达式引擎将(s)作为一个组.我希望它像一个字符串一样对待它"(s)".我可以运行replace用户输入并替换(with \(和)with \)但问题是我需要替换每个可能的正则表达式符号.你知道更好的方法吗?
我需要一个python正则表达式来检查字符串中是否存在单词.该字符串可能以逗号分隔.
所以,例如,
line = 'This,is,a,sample,string'
Run Code Online (Sandbox Code Playgroud)
我想基于"样本"进行搜索,这将返回true.我很喜欢reg ex,所以当我查看python文档时,我看到了类似的内容
import re
re.match(r'sample', line)
Run Code Online (Sandbox Code Playgroud)
但我不知道为什么在文本匹配之前会有'r'.有人可以用正则表达式帮助我吗?
我不理解python正则表达式中scape运算符\的功能以及原始字符串的r'的逻辑。一些帮助表示赞赏。
码:
import re
text=' esto .es 10 . er - 12 .23 with [ and.Other ] here is more ; puntuation'
print('text0=',text)
text1 = re.sub(r'(\s+)([;:\.\-])', r'\2', text)
text2 = re.sub(r'\s+\.', '\.', text)
text3 = re.sub(r'\s+\.', r'\.', text)
print('text1=',text1)
print('text2=',text2)
print('text3=',text3)
Run Code Online (Sandbox Code Playgroud)
该理论说:反斜杠字符('\')表示特殊形式或允许使用特殊字符而无需调用特殊含义。
就此问题末尾提供的链接而言,r'表示原始字符串,即符号没有特殊含义,它保持不变。
所以在上面的正则表达式中,我希望text2和text3是不同的,因为替换文本是'。'。在文本2中,即句点,而(原则上)文本3中的替代文本为r'。这是一个原始字符串,即应显示的字符串,反斜杠和句点。但它们的结果相同:
结果是:
text0= esto .es 10 . er - 12 .23 with [ and.Other ] here is more ; puntuation
text1= esto.es 10. er- 12.23 with [ and.Other ] here is more; puntuation
text2= esto\.es 10\. er …Run Code Online (Sandbox Code Playgroud) 我正在尝试a && b || c && d || e在两者上拆分字符串&&并||使用 re.split。我知道你可以通过做多个分隔符re.split("a | b"),但是我不知道如何实现这个:re.split("&& | ||")。我试图通过使用来逃避管道,re.split("&& | \\|\\|")但这不起作用。
我如何正确地逃避这个?
python ×6
regex ×5
rawstring ×2
backslash ×1
python-2.x ×1
split ×1
string ×1
substitution ×1
unicode ×1