-3

I have a String like this:

123,TV,August 14, 2020,"This is a fantasy series, and top rated"

I'm using String.split() on this but my delimiter should only separate the string based on comma with no trailing space.

Expected Output

["123","TV","August 14, 2020","This is a fantasy series, and top rated"]

Actual Output

["123","TV","August 14"," 2020","This is a fantasy series", " and top rated"]

It is splitting the strings considering all the commas. I just want to consider the commas with no trailing space or double quotes(").

Can someone please advice me on this?

azro
  • 53,056
  • 7
  • 34
  • 70
Ishan Pathak
  • 85
  • 1
  • 1
  • 2
  • You should get whoever is producing the string to quote the date field where it contains a comma, i.e. `123,TV,"August 14, 2020","This is a fantasy series, and top rated"`. Then it's in a valid CSV format, so you can use a CSV library to read it e.g. Apache Commons CSV. – Rup May 06 '21 at 11:37
  • 1
    Use `text.split(",(?!\\s)")` – Wiktor Stribiżew May 06 '21 at 11:37
  • Have you done *any* prior research? There are really a lot of questions that explain how to use spit with regular expressions, like: https://stackoverflow.com/questions/7935858/the-split-method-in-java-does-not-work-on-a-dot – GhostCat May 06 '21 at 11:38
  • You can try > String splitBy = ",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)"; it will split by comma and eliminate comma inside double quotes. If you research more you could get it in google very common problem. – Hitesh Kumar May 06 '21 at 11:44
  • ["123","TV","August 14, 2020",""This is a fantasy series, and top rated""]....I also want to remove "" that remain in the string after split – Ishan Pathak May 06 '21 at 13:22

1 Answers1

0

You may combine with a Negative Lookahead (?!\s) to assert there is no space afte the comma

String s = "123,TV,August 14, 2020 ,\"This is a fantasy series, and top rated\"";
List<String> parts = Arrays.stream(s.split(",(?!\\s)"))
        .map(x -> x.replaceAll("^[\"\\s]|[\"\\s]$", ""))
        .collect(Collectors.toList());
for (String p : parts) {
    System.out.println(">>" + p + "<<");
}

>>123<<
>>TV<<
>>August 14, 2020<<
>>This is a fantasy series, and top rated<<
azro
  • 53,056
  • 7
  • 34
  • 70
  • Hi azro, thanks for the repsonse, this works. But I want a regex with a combination of comma without leading space, comma with leading double quotes and double quotes with leading comma. Could you tell me the regex for this? – Ishan Pathak May 06 '21 at 13:09
  • @IshanPathak You can't just add requirements after ^^ edit your initial to post what input/output you want, and I'll see – – azro May 06 '21 at 20:51
  • @IshanPathak i've add a replaceAll in my solutin, see – azro May 06 '21 at 20:55