简体   繁体   English

Java 中的字符串拆分给出了意想不到的结果

[英]String Split in Java Giving Unexpected Results

I have a series of strings with the following format: "animal || type || area ||".我有一系列具有以下格式的字符串:“动物 || 类型 || 区域 ||”。

In Java, I'm trying to split the string so I can just the first part.在 Java 中,我试图拆分字符串,这样我就可以只使用第一部分。 Everything I have read online says to split the string:我在网上阅读的所有内容都说拆分字符串:

String animalString = "animal || type || area"
String animalArray[] = animalString.split("||")

System.out.println("result = " + Arrays.toString(animalArray));

However, when I split the string it doesn't merely split based on the '||'但是,当我拆分字符串时,它不仅仅基于“||”进行拆分division but instead splits every letter:除法而是拆分每个字母:

result = [a, n, i, m, a, l,  , |, |,  , t, y, p, e,  , |, |,  , a, r, e, a,  , |, |]

When I add a delimiter to the split method, it delimits the first part of the string, so that is not effective.当我向 split 方法添加分隔符时,它会分隔字符串的第一部分,因此无效。

How can I split a string that has the above format so I can get the three words themselves in an array and not just the letters?如何拆分具有上述格式的字符串,以便我可以在数组中获取三个单词本身而不仅仅是字母?

You need to double escape them.你需要双重逃避他们。 Once for the String and once for the regex .一次用于String一次用于regex \\ escapes the slash so it can be passed on to the regex as \| \\转义斜杠,以便它可以作为\|传递给正则表达式which escapes the |逃脱了| . .

The \\s* allows for 0 or more white spaces before and after the || \\s*允许在||前后有 0 个或多个空格

String animalString = "animal || type || area";
String animalArray[] = animalString.split("\\s*\\|\\|\\s*");

System.out.println("result = " + Arrays.toString(animalArray));

prints印刷

result = [animal, type, area]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM