开发者

How to know if a string contains accents

H开发者_运维百科ow to know if a string contains accents?


I think the best thing you can do is using a normalizer that splits unicode characters with accents into two separate character. Java includes this in class Normalizer, see here.

This, for example, will split

U+00C1    LATIN CAPITAL LETTER A WITH ACUTE

into

U+0041    LATIN CAPITAL LETTER A
U+0301    COMBINING ACUTE ACCENT

and will do this for every character that has accents or other diacritical mark (http://en.wikipedia.org/wiki/Diacritic).

Then you can check if the resulting CharSequence has some of the accents character (and this will imply hard coding them) or simply check if the normalized version is equal to the starting one, this will imply that there isn't any character that has been decomposed. Java Normalizer already has this facility in isNormalized(CharSequence src, Normalizer.Form form), but you should check the various forms available to see if there's one suitable for your needs.

EDIT: if you just need basic accent supports (like just è é à ò ì ù) you can just go with oedo option, if you need full support for all the existing accents it would be crazy to hard code them all..


if (Pattern.matches(".*[éèàù].*", input)) {
  ....
}

add whatever accents you want to that list


The right way to do this is to use normalize(str,NFD) fromjava.text.Normalizer, and then delete the characters of general category Mark \pM or Non-Spacing Mark \p{Mn}. Java does not support the standard Unicode property \p{Diacritic} or you could use that. Note that not all Diacritics are Non-Spacing Marks, nor vice versa.

However, this is probably the wrong thing to do. If you are trying to do accent-insensitive string searches and comparisons, the right way to do that is to leave the strings as they are. You need to create a UCA collation object with the level set to 1 (or rather, PRIMARY), then use that to compare your strings. If strings compare equal at the primary strength, it disregards things like accent marks.

Here are examples in Java of how to do that using ICU’s Collator class. If you’re using proper UCA collators, then you don’t have to normalize; they take care of this for you.

This answer in Perl uses two UCA collator objects, one at the primary strength to completely ignore accents for string searches and comparisons, and another that allows diacritics to be distinguished at the secondary strength as is normal for Unicode.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜