Search code examples
pythonregexstringdigits

Search for a string that contains numbers python


So I have the following code:

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()

The line: if '"xe-" + #anynumber + "/" #anynumber + "/" + #anynumber' in line: Is what I'm struggling with syntax-wise.

I am looking to see if a line in the file contains the following string: "xe-number/number/number" (ex: "xe-6/1/10"). It will always have this format, but the numbers will change. What sort of syntax would I use to do this most efficiently.

Thanks!


Solution

  • You can use regular expressions for this. Regular expressions allow you to specify a pattern of text (though not all patterns can be expressed as a regular expression). We can then compile that expression into a Pattern object, and use that object to search strings for the pattern.

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