Python - How to use regular expression in a file, line by line, in Python

Tried to use a different title for the question, but if you can improve the question, do it.

Here is my regular expression: f\(\s*([^,]+)\s*,\s*([^,]+)\s*\)

I would have to apply this in a file, line by line. Line by line in order, simple reading from file and loop. But how to apply regex to strings?

Thanks for the help and sorry for the noob question.

+13
source share
7 answers

The following expression returns a list; Each entry in this list contains all matches of your regular expression in the corresponding line.

 >>> import re >>> [re.findall(r'f\(\s*([^,]+)\s*,\s*([^,]+)\s*\)',line) for line in open('file.txt')] 
+18
source

You can try something like this:

 import re regex = re.compile("f\(\s*([^,]+)\s*,\s*([^,]+)\s*\)") with open("my_file.txt") as f: for line in f: result = regex.search(line) 
+8
source
 import re with open('file.txt') as f: for line in f: match = re.search('f\(\s*([^,]+)\s*,\s*([^,]+)\s*\)', line) 

Note that Python automatically compiles and caches the regular expression, so in this case a separate compilation step is not required.

+7
source

Another way to do

 import re [line for line in open('file.txt') if re.match(r'f\(\s*([^,]+)\s*,\s*([^,]+)\s*\)',line)] 
+3
source

use import re , then re.compile() with your template as an argument, and use the resulting match object attribute on each line. something like that.

 import re pat = re.compile(r'f\(\s*([^,]+)\s*,\s*([^,]+)\s*\)') for line in file: # use pat.match, pat.search .. etc 
+1
source

I used this aproach:

 import re #Define the search term: pattern = f\(\s*([^,]+)\s*,\s*([^,]+)\s*\) #Create an empty list: data = [] #then for line in open(r'file.txt'): if line !='': #<-- To make sure the whole file is read word = re.findall(pattFinder1, line) data.append(str(word)) 
0
source
 for line in file: line = re .match("f\(\s*([^,]+)\s*,\s*([^,]+)\s*\)",line) .group(0) 
0
source

All Articles