0

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!

f1sh
  • 9,331
  • 3
  • 22
  • 47
HaPlasma
  • 25
  • 6

3 Answers3

0
    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]
Ryan
  • 590
  • 2
  • 7
  • 1
    this messes up string values that contain a comma. Which is probably the reason why OP doesn't just use `split(",")`. – f1sh Mar 12 '20 at 18:45
  • Updated to handle commas within valid strings. – Ryan Mar 12 '20 at 19:09
  • now it doesnt handle something like `NULL,NULL` – f1sh Mar 12 '20 at 19:27
  • I think that's the limit of regex. The only other thing I can think to do is adding a case for (L,) and then replacing all NUL with NULL. – Ryan Mar 12 '20 at 19:35
0

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);
Ravi Sharma
  • 150
  • 4
-1

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]

ekiryuhin
  • 803
  • 4
  • 19