我是regex的新手,我想通过分割运算符(!,&,((,),|)来获取包含所有字符串的开始位置和结束位置的字符串数组。

例子:

1.  !(AString&BString)|CString
    0123456789

Output should be String Array with all string's start position and end position:
[AString,BString,CString...]
Every String Position:
AString (7 length) => 2 to 8
BString => 10 to 16
CString => 19 to 25


2.  (AString)&(BString)|!(CString)
3.  !(AString|BString)&CString
4.  !(AString&(!(BString|CString))|DString)

最佳答案

除了拆分,您可以进行匹配。 [^()!&|]+匹配任何字符一次或多次,但不匹配()|!&。然后使用matcherobj.start()matcherobj.end()函数找到每个匹配项的开始和结束索引。

String s1 = "!(AString&BString)|CString";
Matcher m = Pattern.compile("[^()!&|]+").matcher(s1);
while(m.find())
{

System.out.println(m.group() + "  => " + m.start() +  " to " + (m.end()-1));

}


输出:

AString  => 2 to 8
BString  => 10 to 16
CString  => 19 to 25

10-06 13:50