我在 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 .
但是,您可以使用美元斜杠字符串在字符串末尾使用反斜杠:
f.replaceAll($/\\/$, '/')
请参阅demo并检查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/$;
关于java - Groovy 文字正则表达式/\\/未编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44431585/