所以我有以下代码:
cus_str = "show configuration " #intiate router command string variable
with open(var) as config_file: #open file
for line in config_file: #line by line reading of file
if '"xe-" + #anynumber + "/" #anynumber + "/" + #anynumber' in line:
line = line.replace('\n' , '').replace('"' , '').replace(']' , '') #removes all extra characters
i = "| except " + (line.split("cust ", 1)[1]) + " " #split the line and save last index (cust name)
cus_str+=i #append to string
config_file.close()
这一行: if '"xe-“+ #anynumber + "/”#anynumber + "/“+ #anynumber‘in line:就是我在语法方面遇到的问题。
我正在查看文件中的某一行是否包含以下字符串:"xe-number/number/number“(例如:"xe-6/1/10")。它将始终具有此格式,但数字将发生变化。我应该使用哪种语法来最有效地实现这一点。
谢谢!
发布于 2018-08-01 04:02:31
为此,您可以使用正则表达式。正则表达式允许您指定文本模式(尽管并非所有模式都可以表示为正则表达式)。然后,我们可以将该表达式compile
到一个Pattern
对象中,并使用该对象为模式search
字符串。
import re
pattern = re.compile(r'"xe-\d+/\d+/\d+"') # \d+ is "one or more digits".
# Everything else is literal
with open(var) as config_file:
for line in config_file:
if pattern.search(line): # will return a Match object if found, else None
...
发布于 2018-08-01 04:09:15
你可以用一个简单的程序测试一个正则表达式,就像用https://pythex.org/这样的在线工具,然后制作你的程序,一个正确的方向的小示例将会是:
import re
config_file = ["xe-6/1/10", "xf-5/5/542", "xe-4/53/32" ]
rex = re.compile(r'xe-[\d]+/[\d]+/[\d]+')
for line in config_file: #line by line reading of file
if rex.search(line):
print(line)
xe-6/1/10
xe-4/53/32
https://stackoverflow.com/questions/51621069
复制相似问题