Python \W用于检测逃逸序列-正则表达式
Python \W用于检测逃逸序列-正则表达式,python,regex,Python,Regex,\W检测以下非单词字符 \\ Backslash (\) \' Single quote (') \" Double quote (") \a ASCII Bell (BEL) \b ASCII Backspace (BS) \f ASCII Formfeed (FF) \n ASCII Linefeed (LF) \r ASCII Carriage Return (CR) \t ASCII Horizontal T
\W
检测以下非单词字符
\\ Backslash (\)
\' Single quote (')
\" Double quote (")
\a ASCII Bell (BEL)
\b ASCII Backspace (BS)
\f ASCII Formfeed (FF)
\n ASCII Linefeed (LF)
\r ASCII Carriage Return (CR)
\t ASCII Horizontal Tab (TAB)
\v ASCII Vertical Tab (VT)
\ooo Character with octal value ooo
\xhh Character with hex value hh
\newline Backslash and newline ignored
下面是两行,第一行以
#
开头(是一个纯注释),第二行是带断断续续注释的多行字符串
# abc # def
1.3.6.1.4.1.555.2.12.6.102 0x04444001 1.3.6.1.4.1.75.2.12.90.901(1,0)\
# xyz
1.3.6.1.4.1.75.2.12.90.902(2,0)\
# ddd
1.3.6.1.4.1.75.2.12.90.903(3,0)
上面的一些行将\
作为最后一个非单词字符
目标是将上述语法构造为单个字符串:1.3.6.1.4.1.555.2.12.6.102 0x04444001 1.3.6.1.4.1.75.2.12.90.901(1,0)1.3.6.1.4.1.75.2.12.90.902(2,0)1.3.6.1.4.1.75.2.12.90.903(3,0)
如何检测每行末尾的反斜杠
\
?因为
print(re.search(r'\\', 'hello\there')) # '\\' in r'hello\there' gives None - Because backslash is interpreted as part of Esc seq
print(re.search(r'\\', r'hello\there')) # '\\' in r'hello\there' gives (5,6) - Because raw string interprets backslash as backslash
print(re.search(r'\\$', 'hellothere\')) # \' & \" is also an escape sequence. So, python could not find end of string literal
print(re.search(r'\\', r'hellothere\')) # python should consider backslash as backslash, but, python could not find end of string literal. No clue..
要获得所需的输出:
你能不能只使用
\\?
你有没有研究过$
在正则表达式中的含义?我建议你去想一想为什么会这样?hellother\`结尾的\有什么影响?我想你对在原始字符串结尾定义反斜杠感到困惑。这就是为什么你不能在源代码和som中使用反斜杠的原因e变通方法:是的,这个问题有解决方案。问题与正则表达式无关,而是与语法有关,但问题仍然存在…print(重新搜索(r'\$,'hellothere\)
不应该工作,而是print(重新搜索(r'\$,r'hellothere\))
应使用原始字符串…因为反斜杠只是一个反斜杠,而不是转义序列的一部分Read@ialarmedalien您的参考答案是:具体来说,原始字符串不能以单个反斜杠结尾(因为反斜杠将转义以下引号字符)。这打破了使用rawstrings的目的…因为它说:如果您想创建一个包含反斜杠的字符串,并且不希望Python尝试将这些反斜杠解释为转义序列,那么您可以创建一个原始字符串。从:即使在原始文字中,引号也可以用反斜杠转义,但反斜杠仍保留在res中例如,r“\”是由两个字符组成的有效字符串文字:反斜杠和双引号;r“\”不是有效的字符串文字(即使是原始字符串也不能以奇数个反斜杠结尾)。具体来说,原始文字不能以单个反斜杠结尾(因为反斜杠将转义下面的引号字符)。好的,我刚刚在答案中添加了相同的内容,现在看到了注释。谢谢你,我的朋友。