Stefan van den Akker
Stefan van den Akker

Reputation: 6999

Groovy literal regex /\\/ is not compiling

I have a path in Windows:

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

I need to convert the backslashes \ to forward slashes /. Using Java syntax, I would write:

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

But I am studying Groovy, so I thought I would write a literal regular expression:

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

This throws a compilation error:

unexpected token: ) == at line: 4, column: 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?

Upvotes: 2

Views: 2018

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626758

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.

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

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/$;

Upvotes: 2

Related Questions