在 python 字符串中转义“\”字符 [需要避免十六进制编码]
Escape "\" character in python string [need to avoid hexa encoding]
需要从这个字符串中选择 IP 地址
str1 = '<.1.1.1\testdata>'
实施以下选项时
1.
reg = re.compile("^.*\/+([\d\.]+)/\+.*$",re.I).search
mth = reg(str2)
mth.group(1)
收到错误消息
Traceback (most recent call last):
File "<pyshell#90>", line 1, in <module>
mth.group(1)
AttributeError: 'NoneType' object has no attribute 'group'
选项 2。
str1 = "<.1.1.1\cisco>"
str1.replace("\","\\")
print str1
output - '<\t.1.1.1\\cisco>'
尝试将 str1 设为原始字符串
str1 = r"<.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'
您应该使用原始字符串形式:
str1 = r"<.1.1.1\cisco>"
print re.search(r'\b\d+(?:\.\d+)+\b', str1).group()
11.1.1.1
str1 = r'<.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)
需要从这个字符串中选择 IP 地址
str1 = '<.1.1.1\testdata>'
实施以下选项时
1.
reg = re.compile("^.*\/+([\d\.]+)/\+.*$",re.I).search
mth = reg(str2)
mth.group(1)
收到错误消息
Traceback (most recent call last):
File "<pyshell#90>", line 1, in <module>
mth.group(1)
AttributeError: 'NoneType' object has no attribute 'group'
选项 2。
str1 = "<.1.1.1\cisco>"
str1.replace("\","\\")
print str1
output - '<\t.1.1.1\\cisco>'
尝试将 str1 设为原始字符串
str1 = r"<.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'
您应该使用原始字符串形式:
str1 = r"<.1.1.1\cisco>"
print re.search(r'\b\d+(?:\.\d+)+\b', str1).group()
11.1.1.1
str1 = r'<.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)