Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

re.search not able to find the regex pattern inside a file

Tags:

I have test file(test.txt) as below:

`RANGE(vddout,sup)

`RANGE(vddin,sup_p) 

I would like to modify this file as below:

`RANGE(vddout,sup,tol_sup)

`RANGE(vddin,sup_p,tol_sup_p)

Here is the code I tried but its not able to find and the replace the pattern using re.search. Could you point out where is the flaw in the code?

 with open("test.txt", 'r+') as file :
    for line in file:
        print("line={}".format(line))
        findPattern=re.search(r'(`RANGE\(\w+,(\w+))\)',line)
        if findPattern:
            print("findPattern={}".format(findPattern))
            line=re.sub(r'(`RANGE\(\w+,(\w+))\)',r'\1,tol_\2',line)
like image 396
sanforyou Avatar asked Nov 30 '18 02:11

sanforyou


People also ask

How do I find the RegEx pattern?

With RegEx you can use pattern matching to search for particular strings of characters rather than constructing multiple, literal search queries. RegEx uses metacharacters in conjunction with a search engine to retrieve specific patterns. Metacharacters are the building blocks of regular expressions.

What does re search return if nothing found?

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.


1 Answers

As mentioned in the comments, you aren't writing the file.

Moreover, you are reading each line one by one when you could just be reading the entire file as a string to perform your manipulation. This is both inefficient (as you need to perform re.sub multiple times) and more complicated* to code (as you need to create a new string to write to the file).

Finally, you are performing re.match and re.sub. This is unnecessary as re.sub will simply do nothing if there is no match; you don't need to check first.

In [188]: with open('test.txt', 'r+') as f:
     ...:     data = f.read()
     ...:     updated = re.sub(r'(`RANGE\(\w+,(\w+))', r'\1,tol_\2', data)
     ...:     f.seek(0)         # Start writing at the beginning of the file
     ...:     f.write(updated)

*Note: more complex but not difficult

like image 65
aydow Avatar answered Dec 12 '22 23:12

aydow