[英]Java String Split with delimiters attached to the characters between demiliters
I have String like 我喜欢String
Client Name:##USERNAME## Age:##AGE## xyzed
I want to Split is like this 我想拆分是这样的
[Client Name:][##USERNAME##][ Age:][##AGE##][ xyzed]
I tried this regex (?=(##(\\\\w+)##))
it returned 我试过这个正则表达式
(?=(##(\\\\w+)##))
它返回了
[Client Name:][##USERNAME## Age:][##AGE## xyzed]
as in java look-behind doesn't work with variable length so can not use 因为在java中,look-behind不能使用可变长度,因此无法使用
(?=(##(\\w+)##))|(?<=(##(\\w+)##))
If you're happy with a giant hard-coded upper limit, this will work: 如果您对巨大的硬编码上限感到满意,这将有效:
(?=##\\w+##)|(?<=##\\w{1,1000}##)
(I also removed some of those excess brackets) (我也删掉了一些多余的括号)
This: 这个:
String string = "Client Name:##USERNAME## Age:##AGE## xyzed";
String regex = "(?=##\\w+##)|(?<=##\\w{1,1000}##)";
String[] arr = string.split(regex);
System.out.println(Arrays.asList(arr));
Prints: 打印:
[Client Name:, ##USERNAME##, Age:, ##AGE##, xyzed]
Here's an alternative, but it may be too specific to the input: 这是另一种选择,但它可能对输入过于具体:
(?=##\\w)|(?= )(?<=##)
It also works . 它也有效 。
This should work fine, and just involves global replaces: 这应该工作正常,只涉及全局替换:
String Name = "Client Name:##USERNAME## Age:##AGE## xyzed";
String[] parts = Name.replaceAll(":##",":@##").replaceAll("## ",":##@ ").split("@");
System.out.println(Arrays.asList(parts));
Prints: 打印:
[Client Name:, ##USERNAME:##, Age:, ##AGE:##, xyzed]
It's quite simple to read, but it's probably slower than Dukeling's answer. 它的阅读非常简单,但它可能比Dukeling的答案要慢 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.