I have a string that contains source code of an other groovy file in the following format.
def str = "def testcaseObject{
var1: "abc" ,
var2: obj.map['abc'] ,
var3: "xyz" ,
var4: obj.get(0) ,
var5: obj.random() ,
....... "
Within the source file, some of the attributes are strings by default like abc and xyz and few others are functions like obj.map, obj.get, etc.
I want to make these function calls be considered as a string i.e for all occurrences of strings starting with obj, I would like to insert a double quote before obj and double quote exactly before the comma that ends the line.
In the end I would like the above string to be modified as
def str = "def testcaseObject{
var1: "abc" ,
var2: "obj.map['abc'] ",
var3: "xyz" ,
var4: "obj.get(0) ",
var5: "obj.random() ",
....... "
How can I achieve this using a simple replaceAll method using regular expressions in groovy?
This code seems to do what you wanted:
As it prints out:
Explanation of the Regex
The regular expression
/(?m)(.*)(obj.+) ,/falls into 3 parts;(?m)Tells groovy to use a multi-line match (so it will apply the regexp to each line in turn)(.*)which means “one or more characters” this will go into$1in the replacement(obj.+)so it looks for the stringobjfollowed by one or mor characters. THis will go into$2in the replacementSo, for each line which matches:
some_textfollowed byobjfollowed by some text followed by 2 spaces and a comma, it will replace this whole line with:where
$1is the.*group and $2 is the(obj.*)groupHope this explains it 🙂