简体   繁体   中英

Java String Split with delimiters attached to the characters between demiliters

I have String like

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

[Client Name:][##USERNAME## Age:][##AGE## xyzed]

as in java look-behind doesn't work with variable length so can not use

(?=(##(\\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]

Test .

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.

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.

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