gpt4 book ai didi

java - 从命令行读取时将空元素插入到 ArrayList 中

转载 作者:行者123 更新时间:2023-11-30 03:28:00 25 4
gpt4 key购买 nike

我正在运行代码,使用以下代码从给定用户的命令行获取用户组列表:

private ArrayList<String> accessGroups = new ArrayList<String>();

public void setAccessGroups(String userName) {
try {
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec("/* code to get users */");

BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));

String line = null;

// This code needs some work
while ((line = input.readLine()) != null){
System.out.println("#" + line);
String[] temp;
temp = line.split("\\s+");
if(line.contains("GRPNAME-")) {
for(int i = 0; i < temp.length; i++){
accessGroups.add(temp[i]);
}
}
}
// For debugging purposes, to delete
System.out.println(accessGroups);

} catch (IOException e) {
e.printStackTrace();
}
}

获取用户的代码返回包含以下内容的结果:

#Local Group Memberships      *localgroup1          *localgroup2      
#Global Group memberships *group1 *group2
# *group3 *group4
# *GRPNAME-1 *GRPNAME-2

该代码旨在提取以 GRPNAME- 开头的任何内容。这工作正常,只要我打印我得到的 ArrayList 即可:

[, *GRPNAME-1, *GRPNAME-2]

有一个对""字符串的引用。有没有一种简单的方法可以更改正则表达式,或者可以尝试使用其他解决方案来消除添加时发生的情况。

预期输出是:

[*GRPNAME-1, *GRPNAME-2]

编辑:回答、编辑输出以反射(reflect)代码中的更改。

最佳答案

而不是此片段中呈现的标记化:

line.split("\\s+");

使用模式来匹配 \S+ 并将它们添加到您的集合中。例如:

// Class level
private static final Pattern TOKEN = Pattern.compile("\\S+");

// Instance level
{
Matcher tokens = TOKEN.matcher(line);
while (tokens.find())
accessGroups.add(tokens.group());
}

关于java - 从命令行读取时将空元素插入到 ArrayList 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29704594/

25 4 0