开发者

Retrieve characters from a string

开发者 https://www.devze.com 2023-03-10 08:16 出处:网络
What is the best way to get a list of characters [a-z] from a string ignoring any other special charac开发者_运维技巧ter or number?You could use a regular expression:

What is the best way to get a list of characters [a-z] from a string ignoring any other special charac开发者_运维技巧ter or number?


You could use a regular expression:

String lettersOnly = original.replaceAll("[^a-z]", "");

or

String lettersOnly = original.replaceAll("[^a-zA-Z]", "");

While you can use Unicode groups too, I personally find it easier to recognise and understand a simple set such as a-z or a-zA-Z - it means I don't need to look up whether it will include non-ASCII characters :)


Limiting yourself to a-z might remove characters you want. e.g. it remove uppercase and letters other than a-z. You might prefer to try

String alphaOnly = text.replaceAll("[^\\p{Alpha}]", "");

This includes upper and lower case letters from any language.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号