2015-10-19 53 views
2

需要從這個串 str1 = '<\11.1.1.1\testdata>'逃逸「」字符在python串[需要避免六編碼]

當下列選項實現 1. reg = re.compile("^.*\/+([\d\.]+)/\+.*$",re.I).search mth = reg(str2) mth.group(1)

得到的錯誤消息接IP地址

Traceback (most recent call last): 
    File "<pyshell#90>", line 1, in <module> 
    mth.group(1) 
AttributeError: 'NoneType' object has no attribute 'group' 

選項2.

str1 = "<\11.1.1.1\cisco>" 
str1.replace("\\","\\\\") 
print str1 

output - '<\t.1.1.1\\\\cisco>' 
  • 試圖使STR1作爲原料串

    str1 = r"<\11.1.1.1\cisco>" str2 = str1.replace("\\","/"); print str2 output - '</11.1.1.1/cisco>'

    reg = re.compile("^.*\/+([\d\.]+)/\+.*$",re.I).search mth = reg(str2) mth.group(1)

  • '

    error message - 
    Traceback (most recent call last): 
        File "<pyshell#90>", line 1, in <module> 
        mth.group(1) 
    AttributeError: 'NoneType' object has no attribute 'group' 
    
    +1

    您試圖原始字符串...但只'str1'而不是在正規表達? – TigerhawkT3

    回答

    4

    你應該原始字符串形式:

    str1 = r"<\11.1.1.1\cisco>" 
    print re.search(r'\b\d+(?:\.\d+)+\b', str1).group() 
    11.1.1.1 
    
    1
    str1 = r'<\11.1.1.1\testdata>' 
    reg = re.compile(r"^.*?\\([\d\.]+)\\.*$",re.I) 
    mth = reg.search(str1) 
    
    print mth.group(1) 
    

    您需要在兩個地方使用raw字符串。

    輸出:11.1.1.1

    如果你不想使用raw字符串的正則表達式,你將不得不使用

    reg = re.compile("^.*?\\\([\d\.]+)\\\.*$",re.I)