user3413646
user3413646

Reputation: 167

Split string for plus symbols (+)

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

Answers (1)

Hülya
Hülya

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

Related Questions