Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy split using file.seperator

Tags:

split

groovy

I'm getting an error as follows

Groovy script throws an exception of type class 
java.util.regex.PatternSyntaxException with message = 
Unexpected internal error near index 1
\
 ^

from the Split statement as follows:

 String strClassPath = System.getProperty("java.class.path");
 String[] path = strClassPath.split(System.getProperty("file.separator"));

How should I make this work correctly for both UNIX and Windows systems (that's why I'm using "file.separator")

Many thanks in advance

like image 472
Sean Avatar asked Mar 26 '26 13:03

Sean


1 Answers

This calls java's split(String regexp). So your input must be a regexp (or must be quoted):

import java.util.regex.Pattern

def cp = {path, sep ->
    path.split(Pattern.quote(sep)) 
}

assert cp('C:\\window\\something\\groovy.jar', '\\') == ['C:', 'window', 'something', 'groovy.jar']
assert cp('/usr/local/share/groovy.jar', '/') == ['', 'usr', 'local', 'share', 'groovy.jar']

So much for the regexp/split. If you are after the path, you might be better off using Path. e.g.

assert new File('/usr/local/share/groovy.jar').toPath().collect()*.toString() == ['usr', 'local', 'share', 'groovy.jar']
like image 187
cfrick Avatar answered Mar 29 '26 11:03

cfrick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!