简体   繁体   English

使用 String.split() 在双管道 (||) 上拆分字符串

[英]Splitting a string on the double pipe(||) using String.split()

I'm trying to split the string with double pipe(||) being the delimiter.String looks something like this:我正在尝试使用双管道 (||) 作为分隔符来拆分字符串。字符串看起来像这样:

String str ="user@email1.com||user@email2.com||user@email3.com";

i'm able to split it using the StringTokeniser.The javadoc says the use of this class is discouraged and instead look at String.split as option.我可以使用 StringTokeniser 拆分它。javadoc 说不鼓励使用这个 class,而是将 String.split 作为选项。

StringTokenizer token = new StringTokenizer(str, "||");

The above code works fine.But not able to figure out why below string.split function not giving me expected result..上面的代码工作正常。但无法弄清楚为什么下面的 string.split function 没有给我预期的结果..

String[] strArry = str.split("\\||");

Where am i going wrong..?我哪里错了..?

You must escape every single | 你必须逃避每一个| like this str.split("\\\\|\\\\|") 喜欢这个str.split("\\\\|\\\\|")

String.split() uses regular expressions. String.split()使用正则表达式。 You need to escape the string that you want to use as divider. 您需要转义要用作分隔符的字符串。

Pattern has a method to do this for you, namely Pattern.quote(String s) . Pattern有一个为你做这个的方法,即Pattern.quote(String s)

String[] split = str.split(Pattern.quote("||"));

试试这个:

String[] strArry = str.split("\\|\\|");

You can try this too... 你也可以尝试一下......

String[] splits = str.split("[\\|]+");

Please note that you have to escape the pipe since it has a special meaning in regular expression and the String.split() method expects a regular expression argument. 请注意,您必须转义管道,因为它在正则表达式中具有特殊含义,并且String.split()方法需要正则表达式参数。

Try this 尝试这个

String yourstring="Hello || World";
String[] storiesdetails = yourstring.split("\\|\\|");

For this you can follow two different approaches you can follow whichever suites you best:为此,您可以采用两种不同的方法,您可以采用最适合的套件:

Approach 1:方法一:

By Using String SPLIT functionality通过使用 String SPLIT 功能

String str = "a||b||c||d";
String[] parts = str.split("\\|\\|");

This will return you an array of different values after the split:这将在拆分后返回一个包含不同值的数组:

parts[0] = "a"
parts[1] = "b"
parts[2] = "c"
parts[3] = "d"

Approach 2:方法二:

By using PATTERN and MATCHER通过使用 PATTERN 和 MATCHER

import java.util.regex.Matcher;
import java.util.regex.Pattern;

String str = "a||b||c||d";

Pattern p = Pattern.compile("\\|\\|");
Matcher m = p.matcher(str);

while (m.find()) {
    System.out.println("Found two consecutive pipes at index " + m.start());
}

This will give you the index positions of consecutive pipes:这将为您提供连续管道的索引位置:

parts[0] = "a"
parts[1] = "b"
parts[2] = "c"
parts[3] = "d"

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

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