简体   繁体   English

Java用逗号或0(零)后跟空格分隔字符串

[英]Java Split a String with coma or 0(zero) followed by a whitespace

If I have a string, eg 如果我有一个字符串,例如

 s = "david,marko,rita,0 megan,0 vivian,law";

I need split this string into 我需要将这个字符串分成

david
marko
rita
megan
vivian
law

I am trying with 我正在尝试

String arr[] = s.split("[,\\s]");

but didn´t work. 但是没有用。 Any suggestions? 有什么建议么?

You could use this expression: 您可以使用以下表达式:

String arr[] = s.split(",0?\\s*");

Or maybe even: 甚至:

String arr[] = s.split("[,0\\s]+");

Which one you want is unclear from the example. 从示例中不清楚您想要哪一个。

Your regex is : "(,0 |,)" 您的正则表达式为:“(,0 |,)”

So try this code : 因此,请尝试以下代码:

public static void main(String[] args){
        String s = "david,marko,rita,0 megan,0 vivian,law";
        String[] ss = s.split("(,0 |,)");
        for (int i = 0; i < ss.length; i++) {
            String string = ss[i];
            System.out.println(string);
        }
    }

Just an advice Rather then splitting with multiple values try this 只是一个建议,而不是用多个值分割尝试

import java.util.*;
class test {
  public static void main(String[] args) {
    String s = "david,marko,rita,0 megan,0 vivian,law";
    System.out.println(Arrays.toString(s.replace("0","").replace(" ","").split(",")));
  }
}

You can try this: 您可以尝试以下方法:

public class SplitTest {

    public static void main(String[] args) {
        String inputString = "david,marko,rita,0 megan,0 vivian,law";
        String splits[] = inputString.split(",0?\\s*");
        for (String split : splits) {
            System.out.println(split);
        }
    }
}
String[] arr = s.split(",(0\\s+)*");

The regex splits on a comma followed optionally by a 0 and one or more spaces. 正则表达式以逗号分隔,后跟一个0和一个或多个空格。

      public static void main(String[] args) {
         String s = "da0vid,marko,rita,0 megan,0 vivian,law";
         String[] arr = s.split(",(0\\s+)*");
         for (int i = 0; i < arr.length; i++)
           System.out.println("'"+arr[i]+"'");
      }

=>
'da0vid'
'marko'
'rita'
'megan'
'vivian'
'law'

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

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