Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use regexp on file, line by line, in Python

Tags:

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 apply the regexp to the lines?

Thanks for all the help, and sorry for the noob question.

like image 842
Apache Avatar asked May 31 '11 11:05

Apache


People also ask

How do you find the pattern of a file in Python?

write() function and close the file. Define a pattern which you want to find inside the file. Now, open the file in the read form. Use the for loop, and inside that, use the re.search() method to find the pattern and if it searches the match, then print the output.

What is \b in Python regex?

Inside a character range, \b represents the backspace character, for compatibility with Python's string literals. Matches the empty string, but only when it is not at the beginning or end of a word.

Can you use regex in Python?

Python has a module named re to work with regular expressions. To use it, we need to import the module. The module defines several functions and constants to work with RegEx.


2 Answers

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 in open('file.txt')] 
like image 155
phynfo Avatar answered Oct 11 '22 10:10

phynfo


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) 
like image 37
Cédric Julien Avatar answered Oct 11 '22 12:10

Cédric Julien