Reputation: 2595
I'm struggling with regex here.
How do I replace whitespaces with hyphens and allow only a-z symbols?
public String filterSpeciesName(String species) {
return species.replaceAll("[^a-zA-Z]", "").toLowerCase();
}
An example would be
input string "Bar''r$ack Put1in"
output string "barrack-putin"
Upvotes: 0
Views: 870
Reputation: 120644
return species.trim().replaceAll("\\s", "-").replaceAll("[^a-zA-Z-]", "").toLowerCase();
Upvotes: 2
Reputation: 9618
To replace any space character by hyphens, use String#replaceAll("\\s", "-")
.
Then, if you want to simply remove the characters that are not a-z
, use replaceAll("[^a-zA-Z-]", "")
, assuming you don't want to get rid of your newly added hyphens :)
But I would rather recommend you to maybe just:
species.replaceAll("\\s", "-")
matches ^[a-zA-Z-]+$
Exception
if this is not the caseUpvotes: 0