Trebla
Trebla

Reputation: 1174

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

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.

Upvotes: 2

Views: 6517

Answers (5)

Trần Nam Trung
Trần Nam Trung

Reputation: 113

Simply put your delimiter between []

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

Since [ ] is the regex matches any characters between [ ]. You can also specify a list of delimiters like [*,.+-]

Upvotes: 0

Reimeus
Reimeus

Reputation: 159844

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));

Upvotes: 9

forgivenson
forgivenson

Reputation: 4435

StringUtils.split(s, delimiter);

That will treat the delimiter as just a character, not use it like a regex.

StringUtils is a part of the ApacheCommons library, which is tons of useful methods. It is worth taking a look, could save you some time in the future.

Upvotes: 0

Kevin DiTraglia
Kevin DiTraglia

Reputation: 26078

You can run Pattern.quote on the delimiter before feeding it in. This will create a string literal and escape any regex specific chars:

delimiter = Pattern.quote(delimiter);

Upvotes: 1

Suresh Atta
Suresh Atta

Reputation: 122006

You need not to worry about the character type If you use Pattern

Pattern regex = Pattern.compile(s.charAt(4));
Matcher matcher = regex.matcher(yourString);
if (matcher.find()){
    //do something
}

Upvotes: 1

Related Questions