You can use zero-width matching lookahead and lookbehind combo as alternates.
String equation = "1.5+4.2*(5+2)"; String regex = "(?<=op)|(?=op)".replace("op", "[-+*/()]"); // actual regex becomes (?<=[-+*/()])|(?=[-+*/()]) System.out.println(java.util.Arrays.toString( equation.split(regex) )); // ___ _ ___ _ _ _ _ _ _ // [1.5, +, 4.2, *, (, 5, +, 2, )]
Explanation
[…] is a character class definition (?<=…) is a lookbehind; it asserts that we can match … to the left (?=…) is a lookahead; it asserts that we can match … to the right this|that is alternation - Thus,
(?<=op)|(?=op) matches everywhere after or before op - ... where
op is replaced by [-+*/()], i.e. a character class that matches operators - Note that
- is first here so that it doesn't become a range definition meta character
References
Related questions
More examples of zero-width matching regex for splitting
Here are more examples of splitting on zero-width matching constructs; this can be used to split a string but also keep delimiters.
Simple sentence splitting, keeping punctuation marks:
String str = "Really?Wow!This.Is.Awesome!"; System.out.println(java.util.Arrays.toString( str.split("(?<=[.!?])") )); // prints "[Really?, Wow!, This., Is., Awesome!]"
Splitting a long string into fixed-length parts, using \G
String str = "012345678901234567890"; System.out.println(java.util.Arrays.toString( str.split("(?<=\\G.{4})") )); // prints "[0123, 4567, 8901, 2345, 6789, 0]"
Split before capital letters (except the first!)
System.out.println(java.util.Arrays.toString( "OhMyGod".split("(?=(?!^)[A-Z])") )); // prints "[Oh, My, God]"
A variety of examples is provided in related questions below.
Related questions