目前,我已经尝试使用Character.isUpperCase获得以大写大写开头的单词。然而,现在我只想在一个句子中检索短语,在这个句子中,每个单词的第一个字母都是大写的。我该怎么做呢?
例如:“这是一个例句,使安茂基欧大道1号是安茂基欧的一部分。
我会取回“昂摩基欧大道1号”和“安茂基欧”。
String s = "This is a sample sentence so that Ang Mo Kio Avenue 1 is part of Ang Mo Kio.";
String[] words = s.split("[^a-zA-Z']+");
for (int i = 0; i < words.length; i++) {
if (Character.isUpperCase(words[i].charAt(0))) {
System.out.println(words[i]);
}}真正的意图是提取3个或更多大写单词,可选地后面跟着一个数字。
发布于 2013-11-18 11:30:27
我只想在一个句子中检索短语,其中每个单词的第一个字母都是大写字母。
为此,您需要捕获连续的大写单词,并将它们附加到StringBuilder中。如果小写字母出现,那么初始化StringBuilder。
试试看
StringBuilder answer = new StringBuilder();
String s
= "This is a sample sentence so that Ang Mo Kio Avenue 1 is part of Ang Mo Kio.";
String[] words = s.split("\\s+");
int count=0;
for (int i = 0; i < words.length; i++) {
char firstChar=words[i].charAt(0);
if (Character.isUpperCase(firstChar)
||(count>0 && Character.isDigit(firstChar))) {
answer.append(" "+words[i]);
count++;
} else {
//To avoid less than 3 word apply this logic.
if(count>2){
System.out.println(answer);
}
count=0;
answer = new StringBuilder();
}
}
System.out.println(answer);// Also need to print answer here.输出:
Ang Mo Kio Avenue 1
Ang Mo Kio.发布于 2013-11-18 11:54:22
作为基本的启动代码,您可以尝试以下函数:
private static void printStreetNames(String text) {
List<String> words = new ArrayList<String>();
for (String w : text.split("\\s+")) {
if (Character.isUpperCase(w.charAt(0))) {
words.add(w);
continue;
}
if (w.matches("\\d+") && words.size() > 1) {
words.add(w);
continue;
}
if (words.size() >= 2) {
System.out.println(words);
}
words = new ArrayList<String>();
}
if (words.size() >= 2) {
System.out.println(words);
}
}输出:
[Ang, Mo, Kio, Avenue, 1]
[Ang, Mo, Kio.]不过,也有一些警告。例如,以下内容不能正确解析:Ang Mo Kio 1 1 (因为我们不检查是否已经添加了街道号)。此外,它也不会从解析的街道名称(例如,. )中删除尾随的Kio.,但我将把它留给您作为一个摘录。
https://stackoverflow.com/questions/20046581
复制相似问题