0

I need replaceLast() method in the Groovy script - replace the last substring. It is available in Java, but not in Groovy AFAIK. It must work with regex in the same way as the following replaceFirst.

replaceFirst(CharSequence self, Pattern pattern, CharSequence replacement)
Replaces the first substring of a CharSequence that matches the given compiled regular expression with the given replacement.

EDIT: Sorry not being specific enough. Original string is an XML file and the same key (e.g. Name) is present many times. I want to replace the last one.

<Header>
    <TransactionId>1</TransactionId>
    <SessionId>1</SessionId>
    <User>
       <Name>Bob</Name>
       ...
    </User>
    <Sender>
       <Name>Joe</Name>
       ...
    </Sender>
 </Header>
 ...
 <Context>
    <Name>Rose</Name>
    ...
 </Context>
meolic
  • 1,177
  • 2
  • 15
  • 41
  • 1
    Possible duplicate of [java replaceLast()](https://stackoverflow.com/questions/2282728/java-replacelast) – doelleri Oct 18 '19 at 18:27
  • But I cannot use replaceLast() in Groovy, or maybe I can? How? – meolic Oct 18 '19 at 18:32
  • I have decided to go with the prefix approach instead of searching for the last occurrence. https://stackoverflow.com/a/2329789/1022657 – meolic Oct 21 '19 at 12:10

1 Answers1

3

No idea what replaceLast in Java is...it's not in the JDK... If it was in the JDK, you could use it in Groovy...

Anyway, how about using an XML parser to change your XML instead of using a regular expression?

Given some xml:

def xml = '''<Header>
    <TransactionId>1</TransactionId>
    <SessionId>1</SessionId>
    <User>
       <Name>Bob</Name>
    </User>
    <Sender>
       <Name>Joe</Name>
    </Sender>
    <Something>
       <Name>Tim</Name>
    </Something>
 </Header>'''

You can parse it using Groovy's XmlParser:

import groovy.xml.*

def parsed = new XmlParser().parseText(xml)

Then, you can do a depth first search for all nodes with the name Name, and take the last -1 one:

def lastNameNode = parsed.'**'.findAll { it.name() == 'Name' }[-1]

Then, set the value to a new string:

lastNameNode.value = 'Yates'

And print the new XML:

println XmlUtil.serialize(parsed)
 <?xml version="1.0" encoding="UTF-8"?><Header>
  <TransactionId>1</TransactionId>
  <SessionId>1</SessionId>
  <User>
    <Name>Bob</Name>
  </User>
  <Sender>
    <Name>Joe</Name>
  </Sender>
  <Something>
    <Name>Yates</Name>
  </Something>
</Header>
tim_yates
  • 167,322
  • 27
  • 342
  • 338
  • Huh, I was misleaded by a search engine, had done search and the first line was "string - java replaceLast() - Stack Overflow" - didn't notice that this text is from question and not answer :-) – meolic Oct 18 '19 at 19:33