Groovy: An Idiomatic Way to Replace Captured Groups

I have a string like this: docker login -u username -p password docker-registry-url

.

I am executing a command in a Groovy script with execute

. For debugging purposes, I type the command before executing, but since it contains sensitive data, I am fooling the username and password.

def printableCmd = cmd.toString()

def m = printableCmd =~ /(?:.+) -u (.+) -p (.+) (?:.+)/

if (m.matches() && m[0].size() >= 3) {
  printableCmd = m[0][-1..-2].inject(m[0][0]) { acc, val -> acc.replaceAll(val, "***") }
}

      

The above works as expected and prints docker login -u *** -p *** docker-registry-url

, but I'm wondering if there is a more idiomatic way to do this. Please note that I do not want to delete the captured groups, I just replace them with asterisks, thus making it quite clear that the command is not wrong, but confusing for security reasons.

+3


source to share


2 answers


def cmd='docker login -u username -p password docker-registry-url'
println cmd.replaceAll(/(\s-[up]\s+)(\S+)/,'$1***')

      

Output:



docker login -u *** -p *** docker-registry-url

      

+6


source


I found the following solution using a positive look and feel:



โ€‹def cmd = "docker login -u username -p password docker-registry-url"
println cmd.replaceAll(/(?<=-[up]\s)(\S+)/,"***")

      

+1


source







All Articles