Groovy split using file.seperator

我们两清 提交于 2020-01-24 12:59:06

问题


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


回答1:


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']


来源:https://stackoverflow.com/questions/27257759/groovy-split-using-file-seperator

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!