How to determine whether a character is a letter in Java?

后端 未结 2 1716
醉话见心
醉话见心 2020-12-30 23:08

How do you check if a one-character String is a letter - including any letters with accents?

I had to work this out recently, so I\'ll answer it myself, after the re

2条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-30 23:32

    Just checking if a letter is in A-Z because that doesn't include letters with accents or letters in other alphabets.

    I found out that you can use the regular expression class for 'Unicode letter', or one of its case-sensitive variations:

    string.matches("\\p{L}"); // Unicode letter
    string.matches("\\p{Lu}"); // Unicode upper-case letter
    

    You can also do this with Character class:

    Character.isLetter(character);
    

    but that is less convenient if you need to check more than one letter.

提交回复
热议问题