Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java String.split() Regex

Tags:

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?

like image 676
user677786 Avatar asked Mar 25 '12 00:03

user677786


People also ask

How do you split a string in regex?

To split a string by a regular expression, pass a regex as a parameter to the split() method, e.g. str. split(/[,. \s]/) . The split method takes a string or regular expression and splits the string based on the provided separator, into an array of substrings.

Can we use regex in split a string?

You do not only have to use literal strings for splitting strings into an array with the split method. You can use regex as breakpoints that match more characters for splitting a string.

What is split () in Java?

The method split() splits a String into multiple Strings given the delimiter that separates them. The returned object is an array which contains the split Strings. We can also pass a limit to the number of elements in the returned array.

Can we split string with in Java?

You can use the split() method of java. lang. String class to split a string based on the dot. Unlike comma, colon, or whitespace, a dot is not a common delimiter to join String, and that's why beginner often struggles to split a String by dot.


1 Answers

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.

like image 61
IchBinKeinBaum Avatar answered Oct 02 '22 19:10

IchBinKeinBaum