拆分包含表情符号的字符串
Splitting a String that contains emojis
我需要将可能包含或不包含表情符号的字符串拆分为单个字符列表(保持表情符号完整)。目前,正如所料,任何表情符号都被分成各个部分。
String s = "abc";
String[] tokens = s.split("");
// tokens is ["?","?","?","?","a","b","c","?","?"]
// tokens should be ["","","a","b","c",""]
我想将项目大小保持在最低限度并且几乎没有依赖项,所以我想远离任何第 3 方库。确切的输出类型并不重要,只要我至少可以按顺序遍历标记即可。
您可以匹配并提取由基本字符和该字符之后的任意数量的变音符号组成的所有 Unicode 代码点:
\P{M}\p{M}*+
它匹配除变音符号以外的任何字符,然后匹配任何 0+ 变音符号字符。
import java.util.*;
import java.util.stream.*;
import java.util.regex.*;
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
String s = "abc";
List<String> results = Pattern.compile("\P{M}\p{M}*+").matcher(s)
.results()
.map(MatchResult::group)
.collect(Collectors.toList());
System.out.println(results);
}
}
// => [, , a, b, c, ]
在早期的 Java 版本中,您可以使用
import java.util.regex.*;
//.....
String s = "abc";
List<String> results = new ArrayList<>();
Matcher m = Pattern.compile("\P{M}\p{M}*+").matcher(s);
while (m.find()) {
results.add(m.group());
}
System.out.println(results); // => [, , a, b, c, ]
也可能对您有用
String s = "abc";
String[] arr = s.replaceAll("\p{So}|.", "[=10=][=10=]").split("[=10=]+");
//=> { "", "", "a", "b", "c", "" }
假设您的输入不包含 NUL 字节或 [=13=]
否则您可以使用这种传统的匹配和收集方式:
List<String> arr = new ArrayList<>();
Matcher m = Pattern.compile("\P{So}|.").matcher(s);
while (m.find()) {
arr.add(m.group());
}
System.out.println(arr);
//=> [, , a, b, c, ]
我需要将可能包含或不包含表情符号的字符串拆分为单个字符列表(保持表情符号完整)。目前,正如所料,任何表情符号都被分成各个部分。
String s = "abc";
String[] tokens = s.split("");
// tokens is ["?","?","?","?","a","b","c","?","?"]
// tokens should be ["","","a","b","c",""]
我想将项目大小保持在最低限度并且几乎没有依赖项,所以我想远离任何第 3 方库。确切的输出类型并不重要,只要我至少可以按顺序遍历标记即可。
您可以匹配并提取由基本字符和该字符之后的任意数量的变音符号组成的所有 Unicode 代码点:
\P{M}\p{M}*+
它匹配除变音符号以外的任何字符,然后匹配任何 0+ 变音符号字符。
import java.util.*;
import java.util.stream.*;
import java.util.regex.*;
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
String s = "abc";
List<String> results = Pattern.compile("\P{M}\p{M}*+").matcher(s)
.results()
.map(MatchResult::group)
.collect(Collectors.toList());
System.out.println(results);
}
}
// => [, , a, b, c, ]
在早期的 Java 版本中,您可以使用
import java.util.regex.*;
//.....
String s = "abc";
List<String> results = new ArrayList<>();
Matcher m = Pattern.compile("\P{M}\p{M}*+").matcher(s);
while (m.find()) {
results.add(m.group());
}
System.out.println(results); // => [, , a, b, c, ]
String s = "abc";
String[] arr = s.replaceAll("\p{So}|.", "[=10=][=10=]").split("[=10=]+");
//=> { "", "", "a", "b", "c", "" }
假设您的输入不包含 NUL 字节或 [=13=]
否则您可以使用这种传统的匹配和收集方式:
List<String> arr = new ArrayList<>();
Matcher m = Pattern.compile("\P{So}|.").matcher(s);
while (m.find()) {
arr.add(m.group());
}
System.out.println(arr);
//=> [, , a, b, c, ]