igor.stebliy
igor.stebliy

Reputation: 113

Pattern for Guava Splitter

I need to split String by comma or dot or backslach :

Pattern stringPattern = Pattern.compile("\\s+|,|\\\\|");
Splitter.on(stringPattern).omitEmptyStrings().split(description));

but this pattern don't work , what is wrong ?

Upvotes: 1

Views: 2376

Answers (3)

Olivier Grégoire
Olivier Grégoire

Reputation: 35437

Why not use a CharMatcher?

Splitter.on(CharMatcher.anyOf(",.\\")).omitEmptyStrings().split(description);

Given your simple problem, I don't think you need the regular expressions.

Upvotes: 9

MikeFHay
MikeFHay

Reputation: 9023

The correct regex for comma or dot or backslash is [.,\\], so in Java that's

Pattern.compile("[.,\\\\]")

I do like Olivier's suggestion of CharMatcher though.

Upvotes: 2

kashili kashili
kashili kashili

Reputation: 955

I'd use string.split with the regular expressions. Following should work (I have not tried)

 description.split(",.\\")

Then do null check (as such splitter has extra api for the same).

Patterns are useful for identifying "groups". Any regular expression related splitting can be equally done with strings (instead of pattern)-that is not to discourage from using Guava!

Upvotes: -1

Related Questions