Maverick Maverick - 4 months ago 10
Java Question

Java string delimit regex with word, spaces and special characters

I have two strings:

String one = "D -> B: 24"; // I am expecting array to have ['D','B','24']
String two = "route D -> C"; // expecting array to have ['D','C']


My regex is:

String myarray[] = input.split("\\s*(->|:|\\s)\\s*");


I am unit testing the result, for String one it is working fine and returning me exactly 3 in the array but for second String two it returns an empty space in the array as well.

What am I doing wrong? Please help.

Thanks




The String two returns 3 elements in the array, [ ,'D','C']

Answer

You want capitals and numbers - i.e. [A-Z0-9]+. The simplest approach is to remove all leading and trailing non-matching chars - i.e. [^A-Z0-9]+, then split on non-matching chars, like this:

String myarray[] = input.replaceAll("^[^A-Z0-9]+|[^A-Z0-9]+$", "").split("[^A-Z0-9]+");

BTW your posted code would produce [route, D, C], not [D, C]