Case insensitive String split() method

Use regex pattern [xX] in split

String x = "24X45";
String[] res = x.split("[xX]");
System.out.println(Arrays.toString(res));

You can also use an embedded flag in your regex:

String[] array = test.split("(?i)x"); // splits case insensitive

I personally prefer using

String modified = Pattern.compile("x", Pattern.CASE_INSENSITIVE).matcher(stringContents).replaceAll(splitterValue);
String[] parts = modified.split(splitterValue);

In this way you can ensure any regex will work, as long as you have a unique splitter value


split uses, as the documentation suggests, a regexp. a regexp for your example would be :

"[xX]"

Also, the (?i) flag toggles case insensitivty. Therefore, the following is also correct :

"(?i)x"

In this case, x can be any litteral properly escaped.

Tags:

Java

String

Split