chuckfinley
chuckfinley

Reputation: 2595

Regex: replace whitespaces with hyphens and allow only a-z

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

Answers (2)

Sean Bright
Sean Bright

Reputation: 120644

return species.trim().replaceAll("\\s", "-").replaceAll("[^a-zA-Z-]", "").toLowerCase();

Upvotes: 2

ccjmne
ccjmne

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:

  • match if species.replaceAll("\\s", "-") matches ^[a-zA-Z-]+$
  • throw an Exception if this is not the case
  • return the formatted value otherwise

Upvotes: 0

Related Questions