Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To do this in Regex - code base alterations

Tags:

java

regex

I have a complete Java based code base, where members are named:

String m_sFoo;
Array m_arrKeepThings;

Variable/object names includes both a m_ prefix to indicate a member, and an hungarian notation type indicator.

I'm looking for a way to perform a single time code replacment to (for example on the above to cases):

Array keepThings;
String foo;

Of course there are many other alternatives, but I hope that based on two examples, I'll be able to perform the full change. Performances is not an issue as it's a single time fix.

To clarify, if I had to explain this in lines, it would be:

  1. Match words starting with m_[a-zA-Z].
  2. After m_, drop whatever is there before the first Capital letter.
  3. Change the first capital letter to lower case.
like image 997
JAR.JAR.beans Avatar asked May 19 '26 02:05

JAR.JAR.beans


2 Answers

Check out this post: Regex to change to sentence case

Generally I am afraid that you cannot change the case of letters using regular expressions. I'd recommend you to implement a simple utility (using any language you want). You can do it in java. Just go through your file tree, search for pattern like m_[sidc]([A-Z]), take the captured sequence, call toLowerCase() and perform replace.

Other solution is to search and replace for m_sA, then m_sB, ... m_sZ using eclipse. Total: 26 times. It is a little bit stupid but probably anyway faster than implementing and debugging of your own code.

like image 57
AlexR Avatar answered May 20 '26 15:05

AlexR


If you are really, really sure that the proposed changed won't result in clashes (variables that only differ in their prefix) I would do it with a line of perl:

perl -pi.bak -e "s/\bm_[a-z_]+([A-Z]\w*)\b/this.\u$1/g;" *.java

This will perform an inline edit of your Java sources, while keeping a backup with extension .bak replacing your pattern between word boundaries (\b) capitalising the first letter of the replacement (\u) multiple times per line.

You can then perform a diff between the backup files and the result files to see if all went well.

like image 41
rsp Avatar answered May 20 '26 14:05

rsp