RegEx to split a String either at "," or L," or ",N

183 Views Asked by At

I'm an absolute beginner on learning RegEx. I need to split a string into it's different Substrings, based on multiple conditions.

String:

"abc","def",NULL,"ghi",NULL,"jkl"

should be splitted to

[abc, def, NULL, ghi, NULL, jkl]

Currently I'm using String[] split = line.split("\",\""); to generate all substrings which are enclosed within "..." and seperated by ,. This works fine, but if there is a NULL value (which is not enclosed by "..."), the substrings are splittet incorrect.

Is it possible to split the String into it's Substrings by using a RegEx which splits the String if one of the following conditions is given?

  • ","
  • L,"
  • ",N

Thanks in advance!

3

There are 3 best solutions below

4
Ryan On
    String input = "\"abc\",\"def\",NULL,NULL,\"ghi\",NULL,\"jkl\"";
    String [] split = input.split("(\",\")|(\",)|(,\")|(L,)");
    for (int i = 0; i < split.length; i++) {
        if (split[i].startsWith("\"")) {
            split[i] = split[i].substring(1);
        }
        if (split[i].endsWith("\"")) {
            split[i] = split[i].substring(0, split[i].length() -1);
        }
        if (split[i].equals("NUL")) {
            split[i] = "NULL";
        }
    }

OUTPUT

[abc, def, NULL, NULL, ghi, NULL, jkl]
2
Egor On

I think you don't need regexp. Your problem may be solved with split() and replace() methods.

public static void main(String[] args) {
    String str = "\"abc\",\"def\",NULL,\"ghi\",NULL,\"jkl\"";
    List<String> list = Arrays.stream(str.split(","))
            .map(part -> part.replace("\"", ""))
            .collect(Collectors.toList());
    System.out.println(list);
}

Output:

[abc, def, NULL, ghi, NULL, jkl]

0
Ravi Sharma On

We can first replace all double quotes with an empty string then we can split the resulting string with a delimiter comma. As shown below

String[] strArray = str.replaceAll("\"" , "").split(",");

 String str = "\"abc\",\"def\",NULL,\"ghi\",NULL,\"jkl\"";
 String[] strArray = str.replaceAll("\"" , "").split(",");
 Arrays.asList(strArray).stream().forEach(System.out::println);