搜索包含数字 python 的字符串

Search for a string that contains numbers python

所以我有以下代码:

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")。它将始终采用这种格式,但数字会发生变化。我将使用哪种语法最有效地执行此操作。

谢谢!

您可以为此使用正则表达式。正则表达式允许您指定一种文本模式(尽管并非所有模式都可以表示为正则表达式)。然后我们可以 compile that expression into a Pattern object, and use that object to 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
            ...

听起来像是 Regular Expressions 图书馆的工作!

这个数字是日期吗?您可以限制位数。

from re import search, compile #Import the re library with search
pattern = compile(r"xe-\d{1,2}\/\d{1,2}\/\d{1,2}") #Use this pattern to find lines

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 search(pattern, line): #Returns None if match is not found
            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

正则表达式:xe-\d{1,2}\/\d{1,2}\/\d{1,2} 匹配“xe-”后跟 3 组带斜线分隔符的数字对。每组数字的长度可以是 1 或 2 个字符。

旁注

  • 您不需要关闭 config_file,因为 with 语句会在您退出块时为您完成。

  • 我不确定当模式不匹配时您试图用 cus_str += i 完成什么。就目前而言,它只会重复上一行中相同的 i ,除非您将该行缩进 1 级。或者,如果第一行不包含该模式,则给您一个错误。

你可以用一个简单的程序来测试正则表达式,比如用一些在线工具,比如 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