简体   繁体   English

Python字典自动转义正斜杠

[英]python dictionary autoescapes forward slash

I have a class, and in this class I want to store a variable that contains a regular expression. 我有一个类,在这个类中我想存储一个包含正则表达式的变量。 In this case something to identify an IP address: 在这种情况下,可以识别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})"}

Unfortunately, when I call the variable from a prompt I get this: 不幸的是,当我从提示符下调用变量时,得到以下信息:

>>> a = Foo('sosreport')
>>> a.network_search['regex']
'(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})'

Is it possible to do this? 是否有可能做到这一点? Is there a better way? 有没有更好的办法? I've tried single and double quotes, but can't think of a way around it. 我试过单引号和双引号,但是想不出办法。

The confusion here is between regexes proper and strings. 这里的困惑在于正则表达式和字符串之间。
You build a regex from a string, and if you print a regex (as you are implicitly doing; well, technically you're not actually printing, but getting a string representation) then you get a string. 您从字符串构建一个正则表达式,如果您打印一个正则表达式(隐式执行;从技术上讲,您实际上并不是在打印,而是得到了字符串表示形式),那么您会得到一个字符串。 The string has to show the backslashes as escaped, but the regex's internal representation is actually doing what you want. 该字符串必须将反斜杠显示为转义符,但是正则表达式的内部表示实际上是在执行您想要的操作。

apparently it works anyway... 显然无论如何...

>>> 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM