I have the following pattern:
Jan(COMPANY) &^% Feb(ASP) 567 Mar(INC)
I want the final output to be:
String[] one = {"Jan", "Feb", "Mar"};
String[] two = {"COMPANY","ASP","INC"};
Please help. Anyone!!?
I have the following pattern:
Jan(COMPANY) &^% Feb(ASP) 567 Mar(INC)
I want the final output to be:
String[] one = {"Jan", "Feb", "Mar"};
String[] two = {"COMPANY","ASP","INC"};
Please help. Anyone!!?
A complete example that stores the results in String[] one
and String[] two
would look like this:
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]);
}
}
Iterate across the characters in the string and store what you need.
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[] {});