[英]python dictionary autoescapes forward slash
我有一個類,在這個類中我想存儲一個包含正則表達式的變量。 在這種情況下,可以識別IP地址:
class Foo:
'''a class to parse through an sosreport and begin the cleaning process required in many industries'''
def __init__(self, somefile):
self.version = '0.1'
self.somefile = somefile
self.network_search = {'strings':('foo','bar','foobar','barfoo',), 'regex':"(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})"}
不幸的是,當我從提示符下調用變量時,得到以下信息:
>>> a = Foo('sosreport')
>>> a.network_search['regex']
'(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})'
是否有可能做到這一點? 有沒有更好的辦法? 我試過單引號和雙引號,但是想不出辦法。
這里的困惑在於正則表達式和字符串之間。
您從字符串構建一個正則表達式,如果您打印一個正則表達式(隱式執行;從技術上講,您實際上並不是在打印,而是得到了字符串表示形式),那么您會得到一個字符串。 該字符串必須將反斜杠顯示為轉義符,但是正則表達式的內部表示實際上是在執行您想要的操作。
顯然無論如何...
>>> a = Foo('somefile')
>>> a.network_search['regex']
'(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})'
>>> import re
>>> string1 = 'ip addy is 192.168.1.153 so there'
>>> x=a.network_search['regex']
>>> m = re.search(x,string1)
>>> if m:
... print your IP matches
...
your IP matches
>>> string2 = 'no ip addy so there'
>>> n = re.search(x,string2)
>>> if n:
... print "your IP matches"
...
>>>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.