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!
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.
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.
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.
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.
Another possibility would be to use re.findall() which returns a list:
>>>m = re.findall("\d+", strg)
>>>m
['244216', '267093']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With