Search code examples
javaregexgrailsgroovy

Setter not replacing charactes on string


I am writing a setter for a domain class. What is being saved is an xml that is a response from a web service. It includes the first and last name of the user but that information needs to be masked. So i am trying to accomplish that using regex.

I wrote the following setter method:

public void setOnlineRetroCreditResponse(String xml) {
        xml.replaceAll (/(?<=lastName=)([^\s]+)/){lastName ->
        lastName[0].replace ( lastName[1], "X".multiply (lastName[1].size()))
        }
    onlineRetroCreditResponse = xml
    }

I am expecting a sting like this one: "FFPAccountNumber2=12345 lastName=Doe" to be substituted and saved to the databse like this "FFPAccountNumber2=12345 lastName=XXX" but that is not working as expected. I tested my regex using different online like this one https://www.freeformatter.com/java-regex-tester.html and that does not seem to be the issue.

Any ideas would be appreciated.


Solution

  • There are two things: 1) you do not assign the replaced value back to the xml variable and 2) you are replacing the match explicitly while you can just do the necessary modifications to the value you have captured to return it.

    Actually, you do not even need to capture the non-whitespace character chunk, you may access the whole match in the replaceAll callback. Also, you can use \S instead of [^\s].

    Use

    public void setOnlineRetroCreditResponse(String xml) {
        onlineRetroCreditResponse = xml.replaceAll(/(?<=lastName=)\S+/){lastName ->
          "X".multiply(lastName[0].size()) 
       }
    }