I've already tried adding the matcher.find() and matcher.matches() in order to query matching string values, but still its not working.
I am trying to have 3 group patterns to match, and for my example here, I want to match and find group 1 of pattern enclosed in the first round parenthesis.
public class RegexGroupExample2 {
public static void main(String[] args) {
Pattern pattern = Pattern.compile("(^0\\d{10})(^\\d{10})(^63\\d{10})");
String input = "09187654321";
Matcher m = pattern.matcher(input);
m.find();
// m.matches();
String grp1 = m.group(1);
System.out.println("Group 1 " + grp1);
System.out.println(input);
}
}
Why is the grp1 not being retrieved?, afaik this code should work as I already called .find() or .matches() which is required for using .group() methods.
Attached below is the code that I will have if I dont implement Java Match Group feature just like in the answer which is in link above, I would have at least 5 declaration for each patterns and matchers instead of just one Pattern and Matchers to determine what patterns matched.
private String getInputtedDigitsLocal(final String mobileNumber) {
String extractedMobileNumber = "_";
// final Pattern pattern = Pattern.compile("(^0\\d{10}$)||(^\\d{10}$)||^\\+63\\d{10}$||(^63\\d{10}$)");
// final Matcher matcher = pattern.matcher(mobileNumber);
final Pattern pattern1 = Pattern.compile("^0\\d{10}$");
final Pattern pattern2 = Pattern.compile("^\\d{10}$");
final Pattern pattern3 = Pattern.compile("^\\+63\\d{10}$");
final Pattern pattern4 = Pattern.compile("^63\\d{10}$");
final Matcher matcher1 = pattern1.matcher(mobileNumber);
final Matcher matcher2 = pattern2.matcher(mobileNumber);
final Matcher matcher3 = pattern3.matcher(mobileNumber);
final Matcher matcher4 = pattern4.matcher(mobileNumber);
if (matcher1.find()) {
// test Data 0918765321
extractedMobileNumber = mobileNumber;
} else if (matcher2.find()) {
// test Data 9187654321
extractedMobileNumber = "0" + mobileNumber;
} else if (matcher3.find()) {
//test Data +639187654321
extractedMobileNumber=mobileNumber+"Draft";
} else if (matcher4.find()) {
//test Data 639187654321
extractedMobileNumber=mobileNumber+"Draft";
} else {
extractedMobileNumber="NOT SUPPORTED FORMAT";
}
return extractedMobileNumber;
}