我有这个
String str = "a,pnp,a|pnp,lab2|pnp,a|pnp,lab2,utr,utr";
String[] strings = str.split("|");此代码不会拆分'|‘字符,而是拆分每个字符,如下所示
strings[0] == "a";
strings[1] == ",";诸若此类。
如何才能让它工作起来
strings[0] == "a,pnp,a"
strings[1] == "pnp,lab2"
...发布于 2012-04-15 14:50:20
split()接受正则表达式,而|是为正则表达式OR保留的,因此您需要对其进行转义:
String[] strings = str.split("\\|");或者更好:
String[] strings = str.split(Pattern.quote("|"));发布于 2012-04-15 14:48:48
使用
String[] strings = str.split("\\|");发布于 2012-04-15 14:58:30
正如其他答案所示,您可以转义|符号。就我个人而言,我建议下载Guava并使用Splitter。虽然这可能被认为是对单个语句的过度杀伤力,但根据我的经验,这将是一个罕见的项目,不能通过各种Guava代码来使其更具可读性。
如果可能的话,我个人会使用列表而不是数组,所以:
private static final Splitter PIPE_SPLITTER = Splitter.on('|');
...
// Or an immutable list if you don't plan on changing it afterwards
List<String> strings = Lists.newArrayList(PIPE_SPLITTER.split(str));有可能我只是对正则表达式过于敏感,但我真的不喜欢使用处理正则表达式的API,除非我真的想使用保证它们的模式。
https://stackoverflow.com/questions/10160109
复制相似问题