Regular expressions can be a very powerful tool for searching and replacing. Today I learnt how to replace text using regular expressions. The problem I faced was:
I got these 4 equations from the internet: Basically they give you the 4 parameters for a plane equation Ax+By+Cz=D passing thru 3 points (x1,y1,z1),(x2,y2,z2),(x3,y3,z3)
A = y1 (z2 - z3) + y2 (z3 - z1) + y3 (z1 - z2)
B = z1 (x2 - x3) + z2 (x3 - x1) + z3 (x1 - x2)
C = x1 (y2 - y3) + x2 (y3 - y1) + x3 (y1 - y2)
D = x1 (y2 z3 - y3 z2) + x2 (y3 z1 - y1 z3) + x3 (y1 z2 - y2 z1)
I had to use these equations in my code. But my data structures were quite different. The 3 points were in an array of 3 points having fields x,y,z.
So the required replacements were as like:
x1 with poly->points[0].x
y2 with poly->points[1].y
z3 with poly->points[2].z
so on...(total 9 pairs!)
Also, replace the whitespace by * at appropriate places:
Smart soln:
Open the replace dialog in your editor. Select the "regular expressions" options.
I used netbeans but I think most of the good editors in linux support regular expressions
in find, enter: ([x-z])([1-3])
in replace, enter: poly->points[$2-1].$1
($1 stands for the text matching the contents of the 1st parenthesis in the find regexp. and so on..)
open the replace dialog again(to replace whitespace by * at appropriate places)
in find, enter: ([x-z])(\s)(\()
in replace, enter: $1*$3
This one needs some explanation. \s stands for whitespace. ( needs to be escaped because ( is also a token for regular expression defination syntax.
to replace whitespaces in eqation D, do:
in find, enter: ([x-z])(\s)(p)
in replace, enter: $1*$3
the results:
A = poly->points[1-1].y*(poly->points[2-1].z - poly->points[3-1].z) + poly->points[2-1].y*(poly->points[3-1].z - poly->points[1-1].z) + poly->points[3-1].y*(poly->points[1-1].z - poly->points[2-1].z);
B = poly->points[1-1].z*(poly->points[2-1].x - poly->points[3-1].x) + poly->points[2-1].z*(poly->points[3-1].x - poly->points[1-1].x) + poly->points[3-1].z*(poly->points[1-1].x - poly->points[2-1].x);
C = poly->points[1-1].x*(poly->points[2-1].y - poly->points[3-1].y) + poly->points[2-1].x*(poly->points[3-1].y - poly->points[1-1].y) + poly->points[3-1].x*(poly->points[1-1].y - poly->points[2-1].y);
D = poly->points[1-1].x*(poly->points[2-1].y*poly->points[3-1].z - poly->points[3-1].y*poly->points[2-1].z) + poly->points[2-1].x*(poly->points[3-1].y*poly->points[1-1].z - poly->points[1-1].y*poly->points[3-1].z) + poly->points[3-1].x*(poly->points[1-1].y*poly->points[2-1].z - poly->points[2-1].y*poly->points[1-1].z);
(People might say that writing 1 as 2-1 is inefficient but I'm sure that the c compiler does constant folding while generating the target code)