我有以下模式:
Jan(COMPANY) &^% Feb(ASP) 567 Mar(INC)
我希望最终输出为:
String[] one = {"Jan", "Feb", "Mar"};
String[] two = {"COMPANY","ASP","INC"};
请帮忙。任何人!!?
答案 0 :(得分:4)
将结果存储在String[] one
和String[] 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]);
}
}
答案 1 :(得分:0)
迭代字符串中的字符并存储您需要的内容。
String s = "Jan(COMPANY) &^% Feb(ASP) 567 Mar(INC)";
ArrayList<String> monthsList = new ArrayList<String>();
ArrayList<String> companyList = new ArrayList<String>();
StringBuilder b = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
switch (c) {
case ' ':
b.setLength(0);
break;
case '(':
monthsList.add(b.toString());
b.setLength(0);
break;
case ')':
companyList.add(b.toString());
b.setLength(0);
break;
default:
b.append(c);
break;
}
}
String[] monthArray = monthsList.toArray(new String[] {});
String[] companyArray = companyList.toArray(new String[] {});