Split two points based on Java that do not include a single point

I have a string STR1 written in Java. I want to split it

String str1 = "S1..R1..M1..D2..N3..S1.R1.M1.D2.N3.S1R1M1D2N3";

I want to split the string into the following elements in the array:

S1..,R1..,M1..,D2..,N3..,S1.,R1.,M1.,D2,N3.,S1,R1,M1,N3

I think I have to split the pass three times, first... And then Finally, I brought the letter

First I try to use Split, but I didn't get the expected results:

System.out.println("\n Original String = "+str1+"\nSplit Based on .. = "+Arrays.toString(str1.split("(?<=[..])")));

The result of the above split is:

Original String = S1..R1..M1..D2..N3..S1.R1.M1.D2.N3.S1R1M1D2N3
Split Based on .. = [S1.,.,D2.,S1R1M1D2N3]

I even tried:

("(?<=[.+])").

I'm not sure if I need to pattern / match

I need your help

Solution

Instead of using positive lookbehind, use positive lookahead

String s = "S1..R1..M1..D2..N3..S1.R1.M1.D2.N3.S1R1M1D2N3";
String[] parts = s.split("(?<!\\A)(?=[A-Z]\\d)");
System.out.println("Original = " + s + "\nSplitted = " + Arrays.toString(parts));

Note: before the forward-looking assertion, I used the negative lookbehind assertion, which cannot match the position at the beginning of the string By doing so, it prevents an empty element from being the first item in the list

yield

Original = S1..R1..M1..D2..N3..S1.R1.M1.D2.N3.S1R1M1D2N3
Splitted = [S1..,N3]

Another method is to match rather than split

String s  = "S1..R1..M1..D2..N3..S1.R1.M1.D2.N3.S1R1M1D2N3";
Pattern p = Pattern.compile("[A-Z]\\d+\\.*"); 
Matcher m = p.matcher(s);

List<String> matches = new ArrayList<String>();
while (m.find()) {
   matches.add(m.group());
}

System.out.println(matches);

yield

[S1..,N3]
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>