0

I have a list containing the data of a command. There is always 3 elements in this list :

> print (command)
['ip1', 'mac1', 'name1']

Sometime the 3rd element expand because the name of the equipment is using multiple word.

> print (command[2]) # name 1
Desk

or

> print (command[2]) # name 1
Living Room

But it can also expand because it containing another result :

> print (command)
['ip1', 'mac1', 'name 1 ip2 mac2 name2']

When i split the third element by blank space, the position of ip2 and mac2 in the new list can change :

> array = command[2].split()
> print (array)
['Desk', '192.168.1.2', 'aa:bb:cc:01:02:03', 'Kitchen']
['Living', 'Room', '192.168.1.10', 'dd:ee:ff:77:88:99', 'Kitchen']

I would like to get ip2 and mac2 from the third element, but i dont know how to search / recognise a string pattern. In bash i would use '#' to replace the changing characters of the adresses and try to match with a if, while i loop through the new list. But in python i can't do #.#.#.# for the ip and the address.

  • This sound like the source of the list should be fixed. – Klaus D. Dec 08 '20 at 10:55
  • 1
    Does this answer your question? https://stackoverflow.com/questions/10086572/ip-address-validation-in-python-using-regex – Karl Dec 08 '20 at 10:56
  • 2
    there is [ipaddress module](https://docs.python.org/3/library/ipaddress.html) as well as Unix filename pattern matching [fnmatch](https://docs.python.org/3/library/fnmatch.html) built in. – Aivar Paalberg Dec 08 '20 at 10:59
  • How can `print (command[2])` print two different things. You question makes little sense to me. – martineau Dec 08 '20 at 11:02

1 Answers1

0

If you are having issues with recognizing string patters I would personally be tempted to just use regular expressions (regex). There's examples for search patters for mac and ip adresses, but you can of course write your own regex as well. To use it you do need to import the re module.

An easy way to match a ip adress would be ((?:\d+\.){3}\d+) and be similar to #.#.#.#.

Here's how it works:

?: At the beginning of the () is to indicate a non capturing group (normally () are used for groups, but in this case I just want to use it to structure my regex)
\d is any digit (0-9)
+ means one or more of them
\. is just a dot (the \ is to escape it)
{3} means repeat the non capturing group 3 times
\d+ is for the last digits.

For reference some more sophisticated approaches for MAC adresses here.

Good luck.

HilbertB
  • 352
  • 1
  • 2
  • 12