Reputation: 11
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
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
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)|(?= )(?<=##)
Upvotes: 3