gpt4 book ai didi

java - 如何使用 Java 标准 API 从字符串中获取特定数据?

转载 作者:行者123 更新时间:2023-12-01 19:21:43 25 4
gpt4 key购买 nike

我有以下模式:

Jan(COMPANY) &^% Feb(ASP) 567 Mar(INC) 

我希望最终的输出是:

String[] one = {"Jan", "Feb", "Mar"};
String[] two = {"COMPANY","ASP","INC"};

请帮忙。有人吗!!?

最佳答案

将结果存储在 String[] oneString[] Two 中的完整示例如下所示:

import java.util.*;
import java.util.regex.*;

public class Main {
public static void main(String[] args) {

String str = "Jan(COMPANY) &^% Feb(ASP) 567 Mar(INC)";

ArrayList<String> monthArr = new ArrayList<String>();
ArrayList<String> dataArr = new ArrayList<String>();

// Part 1: \\b(\\p{Alpha}+): Word boundary, one or more characters
// Part 2: \\(([^)]+)\\): "(", anything but ")" one or more times, ")"
Pattern p = Pattern.compile("\\b(\\p{Alpha}+)\\(([^)]+)\\)");
Matcher m = p.matcher(str);

while (m.find()) {
monthArr.add(m.group(1)); // m.group(1) = "Jan", "Feb" and so on
dataArr.add(m.group(2)); // m.group(2) = "COMPANY, "ASP", and so on
}

String[] one = monthArr.toArray(new String[0]);
String[] two = dataArr.toArray(new String[0]);
}
}

关于java - 如何使用 Java 标准 API 从字符串中获取特定数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3958725/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com