首页 > 解决方案 > 检索分号前的单词

问题描述

我有绳子,

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

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

firstName
lastName
nId

标签: javastring

解决方案


您可以使用正则表达式来定位每个分号后面的单词:

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

推荐阅读