提问者:小点点

检索分号前的单词


我有绳子,

 String str ="public class Person {private String firstName;private String lastName;private int nId;}"

如果我想检索每个分号之前的单词,我该怎么做? 因此输出将是,

firstName
lastName
nId

共2个答案

匿名用户

可以使用正则表达式将每个分号后面的单词作为目标:

public static void main(String[] args) {
    String str ="public class Person {private String firstName;private String lastName;private int nId;}";
    String pattern = "(\\w*);";
    Matcher m = Pattern.compile(pattern).matcher(str);

    while (m.find()) {
        System.out.println(m.group(1));
    }
}

分号后面的单词存储在M.group(1)中。

firstName
lastName
nId

匿名用户

可以按拆分字符串

String[] parts = string.split(";");

然后你可以得到每个部分的最后一个单词

String lastWord = parts.substring(parts.lastIndexOf(" ")+1);