Java String.split() Regex
300,978
Solution 1
String[] ops = str.split("\\s*[a-zA-Z]+\\s*");
String[] notops = str.split("\\s*[^a-zA-Z]+\\s*");
String[] res = new String[ops.length+notops.length-1];
for(int i=0; i<res.length; i++) res[i] = i%2==0 ? notops[i/2] : ops[i/2+1];
This should do it. Everything nicely stored in res
.
Solution 2
str.split (" ")
res27: Array[java.lang.String] = Array(a, +, b, -, c, *, d, /, e, <, f, >, g, >=, h, <=, i, ==, j)
Solution 3
String str = "a + b - c * d / e < f > g >= h <= i == j";
String reg = "\\s*[a-zA-Z]+";
String[] res = str.split(reg);
for (String out : res) {
if (!"".equals(out)) {
System.out.print(out);
}
}
Output : + - * / < > >= <= ==
Solution 4
You could split on a word boundary with \b
Author by
user677786
Updated on July 09, 2022Comments
-
user677786 almost 2 years
I have a string:
String str = "a + b - c * d / e < f > g >= h <= i == j";
I want to split the string on all of the operators, but include the operators in the array, so the resulting array looks like:
[a , +, b , -, c , *, d , /, e , <, f , >, g , >=, h , <=, i , ==, j]
I've got this currently:
public static void main(String[] args) { String str = "a + b - c * d / e < f > g >= h <= i == j"; String reg = "((?<=[<=|>=|==|\\+|\\*|\\-|<|>|/|=])|(?=[<=|>=|==|\\+|\\*|\\-|<|>|/|=]))"; String[] res = str.split(reg); System.out.println(Arrays.toString(res)); }
This is pretty close, it gives:
[a , +, b , -, c , *, d , /, e , <, f , >, g , >, =, h , <, =, i , =, =, j]
Is there something I can do to this to make the multiple character operators appear in the array like I want them to?
And as a secondary question that isn't nearly as important, is there a way in the regex to trim the whitespace off from around the letters?
-
tchrist about 12 yearsDid you try it? You’re going to have a problem.
-
Andrew Morton about 12 yearsOK, I admit it, I tested it in .NET and it worked. Removing the empty entries should be trivial, and removing the spaces in the string is surely easily accomplished with a .replaceAll before applying the Regex.
-
user677786 about 12 yearsWhile not the exact solution, it did give me the idea that worked! Thanks! I'll edit the main post for the solution!
-
Chris White about 12 yearsYeap, this works, just strip off the leading element from the array (which is empty)
-
user677786 about 12 yearsAfter coming back, this seems like the best way to do it. I'd like to have done it in the regex, but this will work perfectly. Thanks!
-
ghosh about 5 yearsAny explanation?