Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java String Split on any character (including regex special characters)

Tags:

java

string

I'm sure I'm just overlooking something here...

Is there a simple way to split a String on an explicit character without applying RegEx rules?

For instance, I receive a string with a dynamic delimiter, I know the 5th character defines the delimiter.

String s = "This,is,a,sample";

For this, it's simple to do

String delimiter = String.valueOf(s.charAt(4));
String[] result = s.split(delimiter);

However, when I have a delimiter that's a special RegEx character, this doesn't work:

String s = "This*is*a*sample";

So... is there a way to split the string on an explicit character without trying to apply extra RegEx rules? I feel like I must be missing something pretty simple.

like image 759
Trebla Avatar asked May 22 '26 16:05

Trebla


1 Answers

split uses a regular expression as its argument. * is a meta-character used to match zero of more characters in regular expressions, You could use Pattern#quote to avoid interpreting the character

String[] result = s.split(Pattern.quote(delimiter));
like image 165
Reimeus Avatar answered May 25 '26 05:05

Reimeus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!