Arpan Das
Arpan Das

Reputation: 1037

Regex for spliting an array on token

I have a String like the following :

String s = 100[leetcode].

Can I split it into a String array using the split() method?

String[] arr = s.split("\\s*]+\\s*");

So the resulting array becomes:

["100"] ["["] ["leetcode"] ["]"].

I am not able to figure out the correct regex required for this. Can anybody help on this?

Upvotes: 1

Views: 51

Answers (1)

The fourth bird
The fourth bird

Reputation: 163457

One option could be to use lookarounds

(?<=\S)(?=[\[\]])|(?<=[\[\]])(?=\S)
  • (?<=\S) Positive lookbehind, if what is on the left is a non whitespace char
  • (?=[\[\]]) Positive lookahead, if what is on the right is either [ or ]
  • | Or
  • (?<=[\[\]]) Positive lookbehind, f what is on the left is either [ or ]
  • (?=\S) Positive lookahead, if what is on the right is a non whitespace char

Regex demo | Java demo

For example in Java

String s = "100[leetcode]";
String[] arr = s.split("(?<=\\S)(?=[\\[\\]])|(?<=[\\[\\]])(?=\\S)");

Upvotes: 1

Related Questions