简体   繁体   English

拆分基于Java中不包括单点的双点

[英]Splitting based on double dots excluding single dot in Java

I have a String str1 below written in Java that I would like to split. 我有一个用Java编写的String str1,我想拆分。

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

I would like to split the string into following elements in an Array: 我想将字符串拆分为数组中的以下元素:

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

I guess I have to go for 3 pass splitting, first with .., next with . 我想我必须先进行3次传球分裂,首先是......,然后是。 and finally with letter. 最后还带着信。

First I tried to split with .., but I do not get expected result: 首先我试着用..分裂,但我得不到预期的结果:

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., ., R1., ., M1., ., D2., ., N3., ., S1., R1., M1., D2., N3., S1R1M1D2N3]

I tried even with: 我甚至试过:

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

Not sure if I need to go for Pattern/Matches. 不确定我是否需要去模式/匹配。

Need your help please. 需要你的帮助。

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 : I used Negative Lookbehind before the lookahead assertion to assert it's impossible to match the position at start of the string. 注意 :在前瞻断言之前我使用了Negative Lookbehind断言它不可能匹配字符串开头的位置。 By doing this it prevents an empty element as the first item in your list. 通过这样做,它可以防止空元素作为列表中的第一项。

Output 产量

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

Another way is to match instead of 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);

Output 产量

[S1.., R1.., M1.., D2.., N3.., S1., R1., M1., D2., N3., S1, R1, M1, D2, N3]

Pass in an intelligent regex for the argument of .split() . .split()的参数.split()一个智能正则表达式。 I'm going to enlighten you and provide you this intelligent regex. 我将启发你并为你提供这个聪明的正则表达式。 ;) ;)

str1.split("(?<=[.\\d])(?=[A-Z]\\d)")

Takes: 注意到:

"S1..R1..M1..D2..N3..S1.R1.M1.D2.N3.S1R1M1D2N3"

Gives: 得到:

["S1..", "R1..", "M1..", "D2..", "N3..", "S1.", "R1.", "M1.", "D2.", "N3.", "S1", "R1", "M1", "D2", "N3"]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM