return the second instance of a regex search in a line

天大地大妈咪最大 提交于 2019-12-10 14:02:30

问题


i have a file that has a specific line of interest (say, line 12) that looks like this:

conform: 244216 (packets) exceed: 267093 (packets)

i've written a script to pull the first number via regex and dump the value into a new file:

getexceeds = open("file1.txt", "r").readlines()[12]
output = re.search(r"\d+", getexceeds).group(0)

with open("file2.txt", "w") as outp:
    outp.write(output)

i am not quite good enough yet to return the second number in that line into a new file -- can anyone suggest a way?

thanks as always for any help!


回答1:


You've got it almost all right; your regex is only looking for the first match though.

match = re.search(r"(\d+).*?(\d+)", getexceeds)
firstNumber = match.group(1)
secondNumber = match.group(2)

Notice that the regex is looking for two capturing groups (in parens) both a sequence of digits. What's between is just anything - .*? means some minimal number of any characters.

Here's a little test I ran from the shell:

>>> str = 'conform: 244216 (packets) exceed: 267093 (packets)'
>>> match = re.search(r"(\d+).*?(\d+)", str)
>>> print match.group(1)
244216
>>> print match.group(2)
267093



回答2:


Another possibility would be to use re.findall() which returns a list:

>>>m = re.findall("\d+", strg) 
>>>m
['244216', '267093']


来源:https://stackoverflow.com/questions/25914002/return-the-second-instance-of-a-regex-search-in-a-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!