使用正则表达式与char分开避免两个char之间

时间:2017-02-03 11:22:20

标签: java regex string split

考虑我有这样的字符串:

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

如何使用,拆分每件事物,避免char1char2之间的所有事情都不是,

我可以使用此正则表达式,(?![^()]*\\))仅在char1 = '('char2 = ')'时分割:

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

我得到了这个结果:

a
b
c
d
e,f,g
h

那么如何概括这一点来使用char1char2中的任何字符。

谢谢。

1 个答案:

答案 0 :(得分:1)

使用匹配的方法:匹配您定义的字符之间的任何子字符串,然后匹配任何不等于,的字符和用户定义的字符。

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));
    }
} 

请参阅Java demo

Pattern.DOTALL用于制作.个匹配换行符 - 以防万一。

请参阅sample code regex demo