Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string in Java to show only sequence of characters

Tags:

java

regex

split

I am trying to split a string like the string below

3x2y3+5x2w3–8x2w3z4+3-2x2w3+9y–4xw–x2x3+8x2w3z4–4

to a table of strings which does not have any number or sign.

That means

a[0]=x
a[1]=y
a[2]=x
a[3]=w

I tried this

split("(\\+|\\-|\\d)+\\d*")

but it seems that it does not work.

like image 741
Anonymous Avatar asked Jan 15 '23 17:01

Anonymous


2 Answers

The following should work:

String[] letters = input.split("[-+\\d]+");
like image 171
Andrew Clark Avatar answered Jan 21 '23 02:01

Andrew Clark


Edit: -

If you want xw to be together in your resulting array, then you would need to split your string: -

String[] arr = str.split("[-+\\d]+");

Output: -

[, x, y, x, w, x, w, z, x, w, y, xw, x, x, x, w, z]

You can replace all the unwanted characters with empty string, and split on empty string.

String str = "3x2y3+5x2w3-8x2w3z4+3-2x2w3+9y-4xw-x2x3+8x2w3z4-4";
str = str.replaceAll("[-+\\d]", "");        
String[] arr = str.split("");       
System.out.println(Arrays.toString(arr));

Note that, this will add an empty string as the first element of your array, which you can handle.

Output: -

[, x, y, x, w, x, w, z, x, w, y, x, w, x, x, x, w, z]

Note that - sign in your question is different. You should replace it with the one on your keyboard. Currently it is not matching - sign.

like image 25
Rohit Jain Avatar answered Jan 21 '23 03:01

Rohit Jain