Reputation: 167
I would like to split a string "this is a string i++"
into [this, is, a, string, i, ++]
.
I tried string.split("\\s|(?=\\+)")
but it will give me [this, is, a, string, i, +, +]
.
May I know how I can keep the 2 plus symbols into one?
Upvotes: 1
Views: 147
Reputation: 3433
Just a simple change in regex: "\\s|(?=\\+)\\b"
\\b
: zero-width word boundary
e.g. "i++".split("\\b")
outputs [i, ++]
Try this:
String[] arr = "this is a string i++".split("\\s|(?=\\+)\\b");
System.out.println(Arrays.toString(arr));
Output:
[this, is, a, string, i, ++]
Upvotes: 4