[英]Groovy literal regex /\\/ is not compiling
I have a path in Windows: 我在Windows中有一个路径:
assert f.toString() == 'C:\\path\\to\\some\\dir'
I need to convert the backslashes \\
to forward slashes /
. 我需要将反斜杠
\\
转换为正斜杠/
。 Using Java syntax, I would write: 使用Java语法,我会这样写:
assert f.toString().replaceAll('\\\\', '/') == 'C:/path/to/some/dir'
But I am studying Groovy, so I thought I would write a literal regular expression: 但是我正在学习Groovy,所以我想写一个字面正则表达式:
assert f.toString().replaceAll(/\\/, '/') == 'C:/path/to/some/dir'
This throws a compilation error: 这将引发编译错误:
unexpected token: ) == at line: 4, column: 42
意外令牌:)==在第4行,第42列
I started looking on the internet, and found several comments suggesting that this particular regex literal would not work, instead you would have to use a workaround like /\\\\+/
. 我开始在互联网上寻找内容,发现一些评论表明该特定的正则表达式文字不起作用,相反,您必须使用
/\\\\+/
类的解决方法。 But this obviously changes the semantics of the regex. 但这显然改变了正则表达式的语义。
I cannot really understand why /\\\\/
does not work. 我真的不明白为什么
/\\\\/
无法正常工作。 Maybe somebody does? 也许有人吗?
The \\
at the end of the slashy string ruins it. 斜线字符串末尾的
\\
破坏了它。
The main point is that you need to separate the \\
from the /
trailing slashy string delimiter. 要点是,您需要将
\\
与/
尾部的斜线分隔符分开。
It can be done in several ways: 它可以通过几种方式完成:
println(f.replaceAll('\\\\', '/')) // Using a single-quoted string literal with 4 backslashes, Java style
println(f.replaceAll(/[\\]/, '/')) // Wrapping the backslash with character class
println(f.replaceAll(/\\{1}/, '/')) // Using a {1} limiting quantifier
println(f.replaceAll(/\\(?:)/, '/')) // Using an empty group after it
See the Groovy demo . 参见Groovy演示 。
However, you may use dollar slashy strings to use the backslash at the end of the string: 但是,您可以使用美元斜杠字符串在字符串末尾使用反斜杠:
f.replaceAll($/\\/$, '/')
See the demo and check this thread : 查看演示并检查此线程 :
Slashy strings : backslash escapes end of line chars and slash,
$
escapes interpolated variables/closures, can't have backslash as last character , empty string not allowed.斜线字符串 :反斜杠转义行末尾的字符和斜杠,
$
转义内插变量/闭包, 不能将反斜杠作为最后一个字符 ,不允许使用空字符串。 Examples:def a_backslash_b = /a\\b/; def a_slash_b = /a\\/b/;
示例:
def a_backslash_b = /a\\b/; def a_slash_b = /a\\/b/;
def a_backslash_b = /a\\b/; def a_slash_b = /a\\/b/;
Dollar slashy strings : backslash escapes only EOL,
$
escapes interpolated variables/closures and itself if required and slash if required, use$$
to have$
as last character or to have a$
before an identifier or curly brace or slash, use$/
to have a slash before a$
, empty string not allowed.美元slashy字符串 :反斜杠仅EOL,
$
如果需要和斜线如果需要的话,可以使用转义插值变量/关闭和自身$$
有$
作为最后一个字符,或者有一个$
标识或大括号之前或斜线,使用$/
在$
之前$
斜杠,不允许使用空字符串。 Examples:def a_backslash_b = $/a\\b/$; def a_slash_b = $/a/b/$; def a_dollar_b = $/a$$b/$;
例如:
def a_backslash_b = $/a\\b/$; def a_slash_b = $/a/b/$; def a_dollar_b = $/a$$b/$;
def a_backslash_b = $/a\\b/$; def a_slash_b = $/a/b/$; def a_dollar_b = $/a$$b/$;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.