0

I need to split my regular expression like "hey,my,name,"john,boy",age,male". when i try to split using (,) its split into hey,my,name,john,boy,age,male. but i need the output as

hey
my
name
john,boy
age
male

 line="hey,my,name,"john,boy",age,male";
    String[] line1 = line.split(",")
           String slNo = line1[0];
           String customerId = line1[1];
           String customerCategory = line1[2];

Output:hey,my,name,john,boy,age,male

user207421
  • 305,947
  • 44
  • 307
  • 483
  • `line`is not valid – jhamon Apr 24 '19 at 10:11
  • looks like a csv parser might be a better option. As these quotes [are designed for escaping a delimiter](https://stackoverflow.com/questions/4617935/is-there-a-way-to-include-commas-in-csv-columns-without-breaking-the-formatting) – online Thomas Apr 24 '19 at 10:17
  • You aren't splitting a regular expression here. You are splitting a line of data. There is no regular expression here at all. – user207421 Apr 24 '19 at 10:37

1 Answers1

3

Rather than split, it will be much easier to use find using this regex to get your desired strings from group1 and if group1 is null then just the whole match,

"([^"]+)"|[^,]+

Regex Demo

Check this Java code,

String s = "hey,my,name,\"john,boy\",age,male";
Pattern p = Pattern.compile("\"([^\"]+)\"|[^,]+");
Matcher m = p.matcher(s);
List<String> words = new ArrayList<>();

while (m.find()) {
    words.add(m.group(1) == null ? m.group() : m.group(1)); // store all the found words in this ArrayList
}

String[] line1 = words.toArray(new String[words.size()]);
String slNo = line1[0];
String customerId = line1[1];
String customerCategory = line1[2];

words.forEach(System.out::println);

Prints the strings as you wanted,

hey
my
name
john,boy
age
male
Pushpesh Kumar Rajwanshi
  • 18,127
  • 2
  • 19
  • 36
  • thanks and i need to assign splitted values into another individuale variables? – Jayaram Rockstar Apr 24 '19 at 10:28
  • 1
    @JayaramRockstar: You can capture all the values in an ArrayList or array and then access them the way you want. Updated my answer where all the found words are stored in a `List` from where you can use the way you tried in your code in your post. – Pushpesh Kumar Rajwanshi Apr 24 '19 at 10:29
  • I've also added your codes in your post to show how you can use the captured values the way you wanted. Let me know if you face any issues. – Pushpesh Kumar Rajwanshi Apr 24 '19 at 10:36