Summary :
http://www.patrickdenis.biz/blog/regular-expressions-special-characters-and-patterns/
. Matches any single character, including white space.
* Matches 0 or more sequences of the pattern.
+ Matches 1 or more sequences of the pattern.
? Matches 0 or 1 occurrences of the pattern.
^ Matches the beginning of the string.
$ Matches the end of the string.
_ (underscore) Matches a comma (,), left brace ({), right brace (}), the beginning of the string, the end of the string, or a space.
\s Match white-space character class
\S Match Digit Character class
\d Match non-white-space character class
[] Construct your own character class, example [*>]+ <— this mean any of these character 1 or more
() Parenthesis to save things
Examples :
. match one character
.+ match as many character
.* match as many character or no character but not new lines
^.+ match as many character starting at the beginning of the line.
^.+$ ^.+ match as many character starting at the beginning of the line up to the end of the line.
\d can be any one digit, \d\d can be any 2 digit. 10.10.10.1 –> ^\d\d would match 10 but ^\d\d\d would failed because “.” inst a digit.
^\s+ would match as many white-space at the beginning of the line
^\S+ would match as many non-white-space at the beginning of the line
\(any character) Need the escape character to be able to show the special character
? Match as small as it can
re library / Raw string for the patterns :
Ex : Cisco IOS Software, C2950 Software ( C2950DATA-UNIVERSALK9-M), Version 12.1T2
import re
re.search(r”regular_expression”, line)
re.search(r”^.*$”, line).group(0) <– will match the entire line
re.search(r”^Cisco.*, Version (\S+) line),.*$”, line).group(0) math entire line
re.search(r”^Cisco.*, Version (\S+) line),.*$”, line).group(1)
re.search(r”^Cisco (.*), Version (\S+) line),.*$”, line).group(1)
Example of why we use that :
os_version = re.search(r”^Cisco (.*), Version (\S+) line),.*$”, line).group(2)
os_software = re.search(r”^Cisco (.*), Version (\S+) line),.*$”, line).group(1)
The better way to this example is to create the variable inside of the code.
re.search(r”^Cisco (.*), Version (?P<serial_number>\S+) line),.*$”, line).groupdict()
match = re.search(r”^Cisco (.*), Version (?P<serial_number>\S+) line),.*$”, line)
match.groupdict()
{serial_number: 12.1T2}
re.search(r”^Cisco (.*)”, line).group(1)
IOS Software, C2950 Software ( C2950DATA-UNIVERSALK9-M), Version 12.1T2
re.search(r”^Cisco (.*?)”, line).group(1)
IOS Software
re.search(r”^Cisco (.*?)”, line).group(0)
Cisco IOS Software
To search from a single output on multiple line, you can use the flags option :
while open(“show_version.txt”) as f:
….output = f.read()
re.search(r”^Processor board ID (.*)$”, output, flags=re.M)
serial_number = re.search(r”^Processor board ID (.*)$”, output, flags=re.M).group(1)