How to filter a Java String to get only alphabet characters?

后端 未结 2 909
北荒
北荒 2021-01-12 12:24

I\'m generating a XML file to make payments and I have a constraint for user\'s full names. That param only accept alphabet characters (a-ZAZ) + whitespaces to separe names

2条回答
  •  走了就别回头了
    2021-01-12 12:54

    You can first use a Normalizer and then remove the undesired 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
    

    Note that this may not work for all and any non-ascii letters in any language - if such a case is encountered the letter would be deleted. One such example is the Turkish i.

    The alternative in that situation is probably to list all the possible letters and their replacement...

提交回复
热议问题