How to extract multiple text 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: How to extract multiple text from a string? (/thread-32715.html) |
How to extract multiple text from a string? - chatguy - Feb-28-2021 Hi All, Would anyone know how to create a list of a substring prior to "==>" ? Example String input: '\r\nExecuting: /usr/bin/dig +short -4 @120.17.72.174 a hello.com\r\n\r\nSun Feb 28 06:49:59\r\n\t20.1.1.1 => 84(%28)\t\r\n\t20.1.1.2 => 111(%37)\t\r\n\tCNAME.RETURNED.COM => 105(%35)\t\r\n\tQueries=300 Duration=3 secs. QPS=100\r\n' Desired List to create from above: ["20.1.1.1","20.1.1.2","CNAME.RETURNED.COM"] Note: There can be more than anywhere from 0 to infinity items in the above list Thank you! CG RE: How to extract multiple text from a string? - buran - Feb-28-2021 something like spam = '\r\nExecuting: /usr/bin/dig +short -4 @120.17.72.174 a hello.com\r\n\r\nSun Feb 28 06:49:59\r\n\t20.1.1.1 => 84(%28)\t\r\n\t20.1.1.2 => 111(%37)\t\r\n\tCNAME.RETURNED.COM => 105(%35)\t\r\n\tQueries=300 Duration=3 secs. QPS=100\r\n' eggs = [item.split('=>')[0].strip() for item in spam.splitlines() if '=>' in item] print(eggs) RE: How to extract multiple text from a string? - bowlofred - Feb-28-2021 How far back from the item are you looking? If you just want everything back to a space then you could look for a (capturing) set of at least one consecutive non-whitespace characters (\S+) , followed by some optional whitespace \s* , and then the target string => .>>> import re >>> re.findall("(\S+)\s*=>", '\r\nExecuting: /usr/bin/dig +short -4 @120.17.72.174 a hello.com\r\n\r\nSun Feb 28 06:49:59\r\n\t20.1.1.1 => 84(%28)\t\r\n\t20.1.1.2 => 111(%37)\t\r\n\tCNAME.RETURNED.COM => 105(%35)\t\r\n\tQueries=300 Duration=3 secs. QPS=100\r\n') ['20.1.1.1', '20.1.1.2', 'CNAME.RETURNED.COM'] |