仅检索String内的大写单词

时间:2015-02-20 10:00:57

标签: java string

我们假设我们有以下字符串:

String string = "Hello my name Is John doe";

我想只获取此字符串中的大写字符串,在本例中为HelloIsJohn

如何在Java中实现这一目标?

4 个答案:

答案 0 :(得分:6)

您可以split字符串并检查每个部分是否为大写的第一个字母:

String string = "Hello my name Is John doe";
List<String> result = new LinkedList<>();

for (String s : string.split(" ")) {
    if (Character.isUpperCase(s.charAt(0))) {
        result.add(s);
    }
}

答案 1 :(得分:3)

使用带有字边界的正则表达式。

public static void main(String... strings) {
    String string = "Hello my name Is John doe";
    String[] arr = string.replaceAll("\\b[a-z]\\w+\\b", "").split("\\s+");
    for (String s : arr) {
        System.out.println(s);
    }
}

O / P:

Hello
Is
John

答案 2 :(得分:0)

将字符串拆分为空格字符,然后遍历每个拆分部分并检查其第一个字母是否为大写。

public static void main(String[] args) {
    String text = "My hovercraft is Full of Eels";
    Collection<String> startingWithCapital = new ArrayList<>();
    for (String part : text.split(" ")) {
        if (Character.isUpperCase(part.charAt(0))) {
            startingWithCapital.add(part);
        }
    }
    // Just to make sure it works
    for (String part : startingWithCapital) {
        System.out.println(part);
    }
}

输出:

My
Full
Eels

答案 3 :(得分:0)

使用正则表达式并遍历所有匹配项:

String line = "Hello my name Is John doe";
Pattern p = Pattern.compile("([A-Z]\\w+)");
Matcher m = p.matcher(line);
while (m.find()) {
    System.out.println(m.group());
}
相关问题