代码之家  ›  专栏  ›  技术社区  ›  overexchange

\用于检测转义序列的w-regex

  •  0
  • overexchange  · 技术社区  · 6 年前

    \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..
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   gaganso    6 年前

    要获得所需的输出:

    1. 逐行读取文件。
    2. 如果最后一个字符是“\”,请将其删除。
    3. 连接修改的行。

    上述操作应提供所需的结果。我认为使用regex只会使解决方案复杂化,而不会带来任何额外的好处。

    引用 doc 词汇分析:

    当“r”或“r”前缀出现时,在 反斜杠包含在字符串中,不做任何更改,并且 反斜杠留在字符串中。例如,字符串文本 r“\n”由两个字符组成:反斜杠和小写'n'。 字符串引号可以用反斜杠转义,但是反斜杠 保留在字符串中;例如,r“\”是有效的字符串文本 由两个字符组成:反斜杠和双引号;r“\”是 不是有效的字符串文本(即使是原始字符串也不能以奇数结尾 反斜杠的数量)。特别是,原始字符串不能以 单反斜杠(因为反斜杠将转义以下引号 性格)。还要注意,后面跟一个换行符的反斜杠是 将这两个字符解释为字符串的一部分,而不是 行继续。