1
votes

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?

1

1 Answers

2
votes

This code seems to do what you wanted:

def str = '''def testcaseObject{
           var1: "abc"               ,
           var2:  obj.map['abc']     ,
           var3: "xyz"               ,
           var4: obj.get(0)          ,
           var5: obj.random()        ,
.......   '''

println( str.replaceAll( /(?m)(.*)(obj.+)  ,/, '$1"$2",' ) )

As it prints out:

def testcaseObject{
           var1: "abc"               ,
           var2:  "obj.map['abc']   ",
           var3: "xyz"               ,
           var4: "obj.get(0)        ",
           var5: "obj.random()      ",
.......   

Explanation of the Regex

The regular expression /(?m)(.*)(obj.+) ,/ falls into 3 parts;

  1. (?m) Tells groovy to use a multi-line match (so it will apply the regexp to each line in turn)
  2. We then get our first group (.*) which means "one or more characters" this will go into $1 in the replacement
  3. Then, there is a second group (obj.+) so it looks for the string obj followed by one or mor characters. THis will go into $2 in the replacement
  4. and the last part "  ," looks for 2 spaces followed by a comma

So, for each line which matches: some_text followed by obj followed by some text followed by 2 spaces and a comma, it will replace this whole line with:

$1"$2",

where $1 is the .* group and $2 is the (obj.*) group

Hope this explains it :-)