Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return the second instance of a regex search in a line

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!

like image 851
captain yossarian Avatar asked Sep 18 '14 13:09

captain yossarian


People also ask

What does regex search return?

re.search(): Finding pattern in text The re.search() function will search the regular expression pattern and return the first occurrence. Unlike Python re. match(), it will check all lines of the input string. If the pattern is found, the match object will be returned, otherwise “null” is returned.

What does re match () return?

The match method returns a corresponding match object instance if zero or more characters at the beginning of the string match the regular expression pattern. In simple words, the re. match returns a match object only if the pattern is located at the beginning of the string; otherwise, it will return None.

What is the difference between re match () and re search ()?

There is a difference between the use of both functions. Both return the first match of a substring found in the string, but re. match() searches only from the beginning of the string and return match object if found.

How do you use two regular expressions in Python?

made this to find all with multiple #regular #expressions. regex1 = r"your regex here" regex2 = r"your regex here" regex3 = r"your regex here" regexList = [regex1, regex1, regex3] for x in regexList: if re. findall(x, your string): some_list = re. findall(x, your string) for y in some_list: found_regex_list.


1 Answers

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

>>>m = re.findall("\d+", strg) 
>>>m
['244216', '267093']
like image 183
Roman Avatar answered Nov 13 '22 05:11

Roman