-1

Consider i have a String like this :

String str = "a,b,c,d," + char1 + "e,f" + char2 + ",g,h,i,j";

How to split every thing with , avoid every thing between char1 and char2 that not ,.

I can use this regex ,(?![^()]*\\)) to split only if char1 = '(' and char2 = ')' like this :

char char1 = '(', char2 = ')';
String str = "a,b,c,d," + char1 + "e,f,g" + char2 + ",h";
String s2[] = str.toString().split(",(?![^()]*\\))");

I get this result :

a
b
c
d
e,f,g
h

So how to generalize this to use any char in char1 and char2.

Thank you.

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140

1 Answers1

1

Use a matching approach: match any substring between the chars you define and then any character not equal to a , and the user-defined chars.

char char1 = '|', char2 = ')';
String str = "a,b,c,d," + char1 + "e,f,g" + char2 + ",h";
String ch1_quoted = Pattern.quote(Character.toString(char1));
String ch2_quoted = Pattern.quote(Character.toString(char2));
List<String> s2 = new ArrayList<>();
Pattern pattern = Pattern.compile(ch1_quoted + "(.*?)" 
                                    + ch2_quoted + "|[^," + ch1_quoted + ch2_quoted + "]+", Pattern.DOTALL);
Matcher matcher = pattern.matcher(str);
while (matcher.find()){
    if (matcher.group(1) != null) {
        s2.add(matcher.group(1));
        System.out.println(matcher.group(1));
    } else {
        s2.add(matcher.group(0)); 
        System.out.println(matcher.group(0));
    }
} 

See the Java demo.

The Pattern.DOTALL is used to make . match line break characters - just in case.

See the sample code regex demo.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563