[英]Regex to get String array by splitting with operators ( ! , & , ( , ) , | ) with all string's start and end position In Java
我是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
您可以使用Strings Split方法:
String givenString= "!(AString&BString)|CString";
String[] stringArray= givenString.split("[!()&|]");//modify regular expression according to your need
這將給我您的數組,其中包含所需的元素以及其他作為""
元素。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.