简体   繁体   English

从 CSV 文件中搜索 IP 地址

[英]Searching IP address from a CSV file

I have a CSV file where the columns contain several strings with IP addresses.我有一个 CSV 文件,其中的列包含几个带有 IP 地址的字符串。 I successfully ran the regex query but it is adding random characters in the output.我成功运行了正则表达式查询,但它在 output 中添加了随机字符。

descr = df.loc[:, 'desc']

arr = []


pat = re.compile("(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)")

for i in descr:

     test = pat.findall(i)
     arr.append(test)

df["IPA"] = arr

It gives IP address output, but I want the output as 10.35.50.4 etc [(10, 35, 50, 4)] and [(10, 35, 50, 3)] .它给出了IP地址Z78E6221F6393D135681DB398F14CE6DZ [(10, 35, 50, 4)]但我想要Z78E62221F6221F6393D1393D1356681DB3981DB398F16DAS398FB398F14ENG 3.398 Q.36DZ4ENG 3.398STZ4ENG.3.39.39.39.398.398.398.398.398.398.398.398 and 3.398; 3.398 Z.3.398; 3.398 Z.3.14.30andy 3.398 [(10, 35, 50, 3)]

You need to transform your groups (Anything inside a parentheses) into non-capturing groups.您需要将您的组(括号内的任何内容)转换为非捕获组。 You can do that by adding a "?:" right after opening the parentheses.您可以通过在打开括号后立即添加“?:”来做到这一点。

pat = re.compile("(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)")

The reason is written on the definition of the function "findall":原因写在function“findall”的定义上:

Return all non-overlapping matches of pattern in string, as a list of strings.返回字符串中模式的所有非重叠匹配,作为字符串列表。 The string is scanned left-to-right, and matches are returned in the order found.从左到右扫描字符串,并按找到的顺序返回匹配项。 If one or more groups are present in the pattern, return a list of groups;如果模式中存在一个或多个组,则返回组列表; this will be a list of tuples if the pattern has more than one group .如果模式有多个组,这将是一个元组列表 Empty matches are included in the result.结果中包含空匹配项。

Therefore it was returning all the groups, numbers inside your address, separately.因此,它会分别返回您地址中的所有组和数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM