How to filter Java string to get only alphabet characters?

I am creating an XML file for making payments, and I have a limit on the full usernames. This parameter accepts only alphabetic characters (a-ZAZ) + spaces to separate first and last names.

I can’t filter it in a simple way, how can I create a regular expression or filter to get the desired result?

Example:

'Carmen López-Delina Santos' should be 'Carmen LopezDelina Santos'

I need to convert the decoration vowels to single vowels as follows: á> a, à> a, â> a, etc .; and also remove special characters in the form of periods, hyphens, etc.

Thanks!

+7
java string regex
source share
2 answers

You can use the Normalizer first, and then remove the unwanted characters:

 String input = "Carmen López-Delina Santos"; String withoutAccent = Normalizer.normalize(input, Normalizer.Form.NFD); String output = withoutAccent.replaceAll("[^a-zA-Z ]", ""); System.out.println(output); //prints Carmen LopezDelina Santos 

Please note that this may not work for all and any letters without ascii in any language - if such a case occurs, the letter will be deleted. One such example is Turkish i .

An alternative in this situation is probably a list of all possible letters and their replacement ...

+12
source share

You can use this removeAccents with a later replaceAll with [^A-Za-z ] :

 public static String removeAccents(String text) { return text == null ? null : Normalizer.normalize(text, Form.NFD) .replaceAll("\\p{InCombiningDiacriticalMarks}+", ""); } 

Normalizer decomposes the source characters into a combination of a base character and a diacritic mark (it can be several characters in different languages). á , é and í have the same sign: 0301 for noting the accent ' .

The regular expression \p{InCombiningDiacriticalMarks}+ will match all such diacritical codes, and we will replace them with an empty string.

And in the caller:

 String original = "Carmen López-Delina Santos"; String res = removeAccents(original).replaceAll("[^A-Za-z ]", ""); System.out.println(res); 

Watch the IDEONE demo

+1
source share

All Articles