I want to write a function to extract various number of values from a String according to a regex pattern:
Here is my function code:
/**
* Get substrings in a string using groups in regular expression.
*
* @param str
* @param regex
* @return
*/
public static String[] regexMatch(String str, String regex) {
String[] rtn = null;
if (str != null && regex != null) {
Pattern pat = Pattern.compile(regex);
Matcher matcher = pat.matcher(str);
if (matcher.find()) {
int nGroup = matcher.groupCount();
rtn = new String[nGroup];
for (int i = 0; i < nGroup; i++) {
rtn[i] = matcher.group(i);
}
}
}
return rtn;
}
When I test it using:
String str = "nets-(90000,5,4).dat";
String regex = "(\\d+),(\\d+),(\\d+)";
String[] rtn = regexMatch(str, regex);
I get:
rtn: [90000,5,4,90000,5]
How can I get rtn to be [90000,5,4] as I expected?