出现如下错误
Groovy script throws an exception of type class
java.util.regex.PatternSyntaxException with message =
Unexpected internal error near index 1
\
^
来自Split语句如下:
String strClassPath = System.getProperty("java.class.path");
String[] path = strClassPath.split(System.getProperty("file.separator"));
我应该如何使它在 UNIX 和 Windows 系统上都能正常工作(这就是我使用“file.separator”的原因)
提前致谢
最佳答案
这调用了 java 的 split(String regexp)
。所以你的输入必须是一个正则表达式(或者必须被引用):
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']
正则表达式/拆分就这么多了。如果您在路径之后,最好使用 Path
。例如
assert new File('/usr/local/share/groovy.jar').toPath().collect()*.toString() == ['usr', 'local', 'share', 'groovy.jar']
关于Groovy 拆分使用 file.separator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27257759/