user2017455
user2017455

Reputation: 11

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+)##))

Upvotes: 1

Views: 183

Answers (2)

MasNotsram
MasNotsram

Reputation: 2273

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.

Upvotes: 0

Bernhard Barker
Bernhard Barker

Reputation: 55649

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.

Upvotes: 3

Related Questions