Extracting Version Number from a String - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Extracting Version Number from a String (/thread-39728.html) |
Extracting Version Number from a String - britesc - Apr-03-2023 Hi, I would like to be able to extract the version number (nimbers and ,) from a string. I can get the result but only if I use 1 type of delimeter I have noticed that sometimes the delimeter changes so would like to have multiple delimeters options. For example import re text = 'mawk/kinetic,now 1.3.4.20200120-3.1 amd64 [installed,automatic]' m = re.search(',now (.+?)-', text) print(m)
print(m.group(0)
print(m.group(1)) In this case m.group(0) contains the answer I need as the delimiter was - but sometimes it can be a + or : as the final delimeterEqually the first delimeter might be ,now 1: For info the string is generated by apt list --installed | grep -i mawk (in this case)So I am getting in a bit of a pickle as I know I should be able to have multiple start delimeters and multiple end delimters, I assume there must be a simpler way of doing this rather than a series of if statements searching to see what is the start and end delimeter in a string and then calling the correct re.search code. Regex is really powerfull and a language unto itself but I've not got much spare capacity in my onbaord mental ROM anymore. Any advice gratefully received. Thanks and kind regards, jB RE: Extracting Version Number from a String - ibreeden - Apr-05-2023 (Apr-03-2023, 05:45 PM)britesc Wrote: In this case m.group(0) contains the answer I need as the delimiter was - but sometimes it can be a + or : as the final delimeterThen you should use: m = re.search(',now (.+?)[-+:]', text)Does that give the results you need? RE: Extracting Version Number from a String - britesc - May-31-2023 Sorry for the delayed response. Not very well. I have managed to use your code with a bit extra to achieve what I required. Thank you very much. |