其他
Java 21 增强对 Emoji 表情符号的处理了
发现一个 Java 21 中有意思的东西!在java.Lang.Character
类中增加了用于确定字符是否为 Emoji 表情符号的 API,主要包含下面六个新的静态方法:
public static boolean isEmoji(int codePoint) {
return CharacterData.of(codePoint).isEmoji(codePoint);
}
public static boolean isEmojiPresentation(int codePoint) {
return CharacterData.of(codePoint).isEmojiPresentation(codePoint);
}
public static boolean isEmojiModifier(int codePoint) {
return CharacterData.of(codePoint).isEmojiModifier(codePoint);
}
public static boolean isEmojiModifierBase(int codePoint) {
return CharacterData.of(codePoint).isEmojiModifierBase(codePoint);
}
public static boolean isEmojiComponent(int codePoint) {
return CharacterData.of(codePoint).isEmojiComponent(codePoint);
}
public static boolean isExtendedPictographic(int codePoint) {
return CharacterData.of(codePoint).isExtendedPictographic(codePoint);
}
这些静态方法通过接收字符的codePoint
来判断是否为表情符号来返回boolean
值。
所以,我们可以用isEmoji
方法来判断字符串中是否有表情,比如:
@Test
void testEmoji() {
String message = "欢迎来到 www.didispace.com ❤️,要不要来杯 ☕️ ?";
if(message.codePoints().anyMatch(Character::isEmoji)) {
System.out.println("Message包含表情");
}
}
除了判断字符串中是否包含表情符号之外,还能用isEmojiModifier
和isEmojiModifierBase
来判断Emoji是否被修改和是否可以被修改:
@Test
void testEmoji2() {
String welcomeMsg ="欢迎来到 www.didispace.com ❤️,要不要来杯 ☕️ ?";
OptionalInt emojiOptional = welcomeMsg.codePoints().filter(Character::isEmoji).findFirst();
if (emojiOptional.isPresent()) {
int emojiCodePoint = emojiOptional.getAsInt();
if (Character.isEmojiModifierBase(emojiCodePoint)) {
System.out.println("Emoji can be modified");
if (Character.isEmojiModifier(emojiCodePoint))
System.out.println("Emoji is modified");
else
System.out.println("Emoji has not been modified");
} else
System.out.println("Emoji cannot be modified");
} else
System.out.println("No emoji present");
}
这些新方法也可以通过属性构造正则表达式来使用,比如:
String welcomeMsg = "欢迎来到 www.didispace.com ❤️,要不要来杯 ☕️ ?";
Matcher matcher = Pattern.compile("\\p{IsEmoji}").matcher(welcomeMsg);
if(matcher.find()) {
System.out.println("Message contains an emoji!");
}
matcher = Pattern.compile("\\p{IsEmoji_Modifier_Base}").matcher(welcomeMsg);
if(matcher.find()) {
System.out.println("Message contains an emoji modifier base!");
}
欢迎关注博客连载的Java新特性专栏:https://www.didispace.com/java-features/
推荐阅读
点击卡片关注我,分享一线前沿干货