如何从Java中的String打印单词以及其后跟的char以获取Specfic长度

时间:2018-10-05 10:58:49

标签: java string

大家好,我遇到了一个小问题,我不知道天气是否可能。在下面的String foo中,我列出了名称以及其所属的地址。所以我的问题是,有没有一种方法可以打印所有name及其后续字符,直到下一个空格。

String foo="Hello my name is name Suryam from India"
          +"Hello my name is name Shekar from Europe"
          +"Hello my name is name Raju from United States"
          +"Hello my name is name Chandramouli from  Bangladesh"
          +"Hello my name is name Ravi from Austrila"
          +"Hello my name is name Sai from Singapore"
          +"Hello my name is name Naresh from Japan";

我希望打印出预期的输出。

输出

name Suryam 
name Shekar
name Raju 
name Chandramouli 
name Suryam 
name Ravi 
name Sai 
name Naresh 

1 个答案:

答案 0 :(得分:1)

您可以使用正则表达式is\\sname\\s(\\w+)\\s来获取数据,请注意每条记录中的重复名称

    String foo="Hello my name is name Suryam from India"
            +"Hello my name is name Shekar from Europe"
            +"Hello my name is name Raju from United States"
            +"Hello my name is name Chandramouli from  Bangladesh"
            +"Hello my name is name Ravi from Austrila"
            +"Hello my name is name Sai from Singapore"
            +"Hello my name is name Naresh from Japan";
    String regex = "is\\sname\\s(\\w+)\\s";
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(foo);
    while(matcher.find()){
        System.out.println("name " + matcher.group(1));
    }

输出:

name Suryam
name Shekar
name Raju
name Chandramouli
name Ravi
name Sai
name Naresh