在Groovy中使用反斜杠 [英] Using backslashes in Groovy
问题描述
我正在使用groovy编写一个脚本,该脚本替换UNC服务器名称和部分目录结构.我有以下内容:
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
\\<服务器> \ share \< env>
具有< server>
和< env>
谢谢!
我想我应该澄清一下.SHARESERVER和OPS实际上是变量.因此,真正的最终结果将是:
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.
我将是第一个承认我对reg ex很烂的人,因此,如果您可以使用它们来捕获字符串中的值并将该值替换为另一个值,那么我将不知所措.
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.
推荐答案
不兼容
def patternToReplace = $/\\SHARESERVER\share\OPS/$
这篇关于在Groovy中使用反斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!