Reputation: 433
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.
Upvotes: 2
Views: 3249
Reputation: 122414
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/)
Upvotes: 1
Reputation: 171194
Doesn't it work with
def patternToReplace = $/\\SHARESERVER\share\OPS/$
Upvotes: 2