I am currently working with a large code base, in which recently one of the API's signature changed. So I need to modify thousands of files to get the new feature. So developed a java program to get take all *.java
files and look for old API pattern. If found replace it with new pattern.
API(3,Utils.FIFTY,key1,key4)
API(key1,key4)
So I created a regex pattern to match the old API as API\([\d,\s\.\w]*(key[\.\w\s,]*)\)
If it matches it will replace it with
replaceString = matcher.group(1) + "(" + matcher.group(2) + ")";
So with the current code instead of expected API(key1,key4)
, I am getting API(key4)
. I've analyzed the issue and my inference is that the \w
caught the first key pattern. If we need to match, we need to do a negative look ahead.
Can any one share the best consistent way to resolve the regex issue ?
Something like the following should work:
API\([\.\w \t,]*?,\s*(key[\.\w \t,]*)\)
The main change here was to change the repetition on the first character class from *
to *?
, this means it will now match as few characters as possible instead of as many as possible, so you all of your key
arguments will be included in your matching group.