1

I'm using groovy to write a script that replaces UNC server names and a part of the directory structure. I have the following:

def patternToFind = /\\\\([a-zA-Z0-9-]+)\\share\\([a-zA-Z]+)/
def patternToReplace = '\\\\\\\\SHARESERVER\\\\share\\\\OPS'

This works, but all those \'s are pretty ugly. I understand in the regex why \\\\ is used to find \\, but what is confusing me is why in the replacement I'm doing I have to use four \'s to equal one \.

If anyone has a nicer way to do this I would greatly appreciate it. The goal is to replace

\\<server>\share\<env>

with the correct value for <server> and <env>

Thanks!

EDIT: I guess I should clarify. SHARESERVER and OPS are actually variables. So truly the end result would be something like:

def serverName = //some passed in server
def env = //some passed in env

def patternToFind = /\\\\([a-zA-Z0-9-]+)\\NAS\\([a-zA-Z]+)/
def patternToReplace = '\\\\\\\\' + serverName + '\\\\share\\\\' + env

So the only way I think of doing it is building a string literal to replace the section I'm looking for with.

And I'll be the first to admit that I suck at reg ex, so if you can use them to capture a value in a string and replace just that value with another, I'm all ears.

2
  • Thanks for the edit! Was trying to figure out how to escape those characters
    – Cthulhujr
    Jun 2, 2014 at 18:59
  • Can't you use the same slashy string format used for patternToFind? /\\\\SHARESERVER\\share\\OPS/
    – dmahapatro
    Jun 2, 2014 at 19:13

2 Answers 2

2

Doesn't it work with

def patternToReplace = $/\\SHARESERVER\share\OPS/$
1
  • Yup it should assert ($/\\SHARESERVER\share\OPS/$ ==~ /\\\\SHARESERVER\\share\\OPS/). Forgot about the $/ dollar slashy string. :)
    – dmahapatro
    Jun 2, 2014 at 19:15
1

If you want to use a literal replacement string (as opposed to one that involves $n backreferences) with a regular expression in Java then the safest thing to do is use Matcher.quoteReplacement:

def patternToReplace = Matcher.quoteReplacement(/\\SHARESERVER\shares\OPS/)
1
  • Ha... well spotted. According to my experiments this doubles single backslashes. Despite the method name... and despite the slightly cryptic Javadoc: "Slashes ('\') and dollar signs ('$') will be given no special meaning" Apr 28, 2018 at 17:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.