Ascertaining how subtract works with Strings in Groovy

Subtracting strings in Groovy is a bit too ambiguous for my liking.
For example, have you ever wondered how the following code would execute:

def a = 'abc xyz abc'
def b = a - 'abc'
println b

Does b result in?:
a) ‘abc xyz ‘ (subtracting right to left)
b) ‘ xyz abc’ (subtracting left to right)
c) ‘ xyz ‘ (a greedy subtract subtracting all instances)

The answer is b!

If you could somehow syntactically specify the three variants in the subtract or specify a starting position to search from in the syntax I’d be a happier camper.
Depending on your needs you’re back to using Regular Expressions, String Replace or some sort of manual splicing of strings with the indexOf variants.

If you want the result specified by c), for example you can do this (courtesy of Venkat’s Programming Groovy P113) The replaceAll is an empty string, two back to back single quotes:

def c = (a =~ /abc/).replaceAll('')

Here’s a few other variants:

def a = 'abc xyz abc'
def b = /abc/
def c = (a =~ b)
def d = c.replaceFirst('')
def e = a.replaceFirst(b, '')
println "d: $d"
println "e: $e"
def st,fin
def cm1 = (c.size() -1)
c.eachWithIndex{m, i ->
  if (i == cm1)  {
    st = c.start()
    fin = c.end()
def p1 = (st == 0) ? '' : a[]
def p2 = (fin == a.size()) ? '' : a[fin..-1]
a = p1+p2
println "a: |$a|"
return null

and the resulting output:

d:  xyz abc
e:  xyz abc
a: |abc xyz |

Here are some associated useful links:


About this entry