Groovy 文字正则表达式 /\\/ 未编译

Groovy literal regex /\\/ is not compiling

我在 Windows 中有一条路径:

assert f.toString() == 'C:\path\to\some\dir'

我需要将反斜杠 \ 转换为正斜杠 /。使用 Java 语法,我会写:

assert f.toString().replaceAll('\\', '/') == 'C:/path/to/some/dir'

但是我正在学习Groovy,所以我想我会写一个文字正则表达式:

assert f.toString().replaceAll(/\/, '/') == 'C:/path/to/some/dir'

这会引发编译错误:

unexpected token: ) == at line: 4, column: 42

我开始在互联网上查找,发现一些评论表明这个特定的正则表达式文字不起作用,相反你必须使用像 /\+/ 这样的解决方法。但这显然改变了正则表达式的语义。

我真的不明白为什么 /\/ 不起作用。也许有人会?

斜线字符串末尾的 \ 破坏了它。

重点是您需要将 \/ 尾部斜杠字符串定界符分开。

可以通过多种方式完成:

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

参见Groovy demo

但是,您可以使用 dollar slashy strings 在字符串末尾使用反斜杠:

f.replaceAll($/\/$, '/')

参见 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/;

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. Examples: def a_backslash_b = $/a\b/$; def a_slash_b = $/a/b/$; def a_dollar_b = $/a$$b/$;