如何在 Java 中用撇号分隔字符串?

How do I separate Strings with an apostrophe in them in Java?

我正在尝试将 "That thereby beauty’s rose might never die," 行分成单独的单词,我的代码有效 - 除了撇号。 "beauty's" 仍返回为 "beauty's" 而不是 "beauty" 和 "s".

这就是我正在尝试的:

String line = "That thereby beauty’s rose might never die,";
String[] words = line.split("[' ,]");

我真的不明白在 Java 中添加多个分隔符,但这似乎适用于除了撇号之外的所有内容。有人可以帮我解决这个问题吗?

仔细查看 line 的撇号和您的拆分撇号。他们是不同的角色。 != '。您很可能希望将第一个转换为第二个。

一些代码供大家琢磨:

String line = "That thereby beauty’s rose might never die,";
String[] words = line.split("[' ,]");
System.out.println(Arrays.toString(words));

line = "That thereby beauty's rose might never die,";
words = line.split("[' ,]");
System.out.println(Arrays.toString(words));

输出:

[That, thereby, beauty’s, rose, might, never, die]
[That, thereby, beauty, s, rose, might, never, die]

'替换为:

String[] words = line.split("[’ ,]");