Skip to content Skip to sidebar Skip to footer

How To Use Regexp On File, Line By Line, In Python

Here is my regexp: f\(\s*([^,]+)\s*,\s*([^,]+)\s*\) I'd have to apply this on a file, line by line. The line by line is OK, simple reading from file, and a loop. But how do I appl

Solution 1:

The following expression returns a list; every entry of that list contains all matches of your regexp in the respective line.

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

Solution 2:

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)

Solution 3:

import re
withopen('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 regex, so a separate compile step is not required in this case.

Solution 4:

Another way to do

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

Solution 5:

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

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

Post a Comment for "How To Use Regexp On File, Line By Line, In Python"