String : USA (45)
using pattern matching getting only numeric value 45
Java code
ArrayList<String> portfolioCount = new ArrayList<String>();
String mainText = USA (45)
final Pattern p = Pattern.compile("\\((.*?)\\)");
final Matcher m = p.matcher(mainText);
m.find();
portfolioCount.add(m.group(1));
store the numeric value into an arrayList, my question is how to store the rest of the String (ie USA) into another array list
Just capture the part before the number within () to another group,
ArrayList<String> portfolioCount = new ArrayList<String>();
String mainText = "USA (45)";
final Pattern p = Pattern.compile("(\\S+)\\s+\\((.*?)\\)");
final Matcher m = p.matcher(mainText);
while(m.find()){
portfolioCount.add(m.group(1));
portfolioCount.add(m.group(2));
System.out.println(portfolioCount);
}
Output
[USA, 45]
To store the country name and count into two separate lists,
ArrayList<String> portfolioCount = new ArrayList<String>();
ArrayList<String> country = new ArrayList<String>();
String mainText = "USA (45)";
final Pattern p = Pattern.compile("(\\S+)\\s+\\((.*?)\\)");
final Matcher m = p.matcher(mainText);
while(m.find()){
portfolioCount.add(m.group(1));
country.add(m.group(2));
System.out.println(portfolioCount);
System.out.println(country);
}
Output:
[USA]
[45]
You can use lookahead and lookbehind in order not to include the parenthesis in the matched group:
ArrayList<String> countryCount = new ArrayList<String>();
ArrayList<String> portfolioCount = new ArrayList<String>();
String mainText = "USA (45)";
final Pattern p = Pattern.compile("(.*?)(?>\\()(\\d+)(?=\\)).*");
final Matcher m = p.matcher(mainText);
m.find();
countryCount.add(m.group(1)); //USA
portfolioCount.add(m.group(2)); //45
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.