[英]Java: Split a string by special characters and spaces
我是java的新手,我必须为一个短语创建一个猪拉丁语翻译器。 这是我现在的代码,以便我可以分割用户输入的短语。 抱歉格式不正确。
String english = "Queen of all reptiles";
String[] words = english.split ("\\s+");
for (int i = 0 ; i < words.length ; i++) {
System.out.println (words [i]);
}
此代码的输出是:
Queen
of
all
reptiles
但是,我想用空格和特殊字符拆分String english,以便if
String english = "Queen. of reptiles."
它会输出:
Queen
.
of
reptiles
.
我试图这样做: String[] words = english.split ("[^a-zA-Z0-9]", "");
但它不起作用。
您可以将以下内容用于字符串大小写。
String s = "Queen. of reptiles.";
String[] parts = s.split("(?=\\.)|\\s+");
System.out.println(Arrays.toString(parts));
产量
[Queen, ., of, reptiles, .]
似乎有一个讨论使用split和look-behinds来实现这一点:
正如Luiggi Mendoza在他的评论中所描述的那样,这将如您所述:
String english = "Queen. of reptiles.";
Pattern p = Pattern.compile("\\w+|\\.");
Matcher m = p.matcher(english);
do {
if (m.find()) {
System.out.println(m.group());
}
} while (!m.hitEnd());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.