I am new to regex , I want to get string array with all string's start position and end position by splitting operator ( ! , & , ( , ) , | ) .
Examples:
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)
Instead of splitting, you could do matching. [^()!&|]+
matches any character but not of (
or )
or |
or !
or &
one or more times. Then find the start and end index of each match using matcherobj.start()
and matcherobj.end()
functions.
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));
}
Output:
AString => 2 to 8
BString => 10 to 16
CString => 19 to 25
You can use Strings Split method:
String givenString= "!(AString&BString)|CString";
String[] stringArray= givenString.split("[!()&|]");//modify regular expression according to your need
This will give me your array which contains element as you wanted plus other element as ""
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.