fork download
  1. import java.util.regex.Matcher;
  2. import java.util.regex.Pattern;
  3.  
  4. public class Main
  5. {
  6. static void printMatch(String regex, String str, int... groups)
  7. {
  8. System.out.println("String = " + str);
  9. System.out.println("Regex = " + regex);
  10. Pattern p = Pattern.compile(regex);
  11. Matcher m = p.matcher(str);
  12. if (m.matches())
  13. for (int i: groups)
  14. System.out.println("Group " + i + " = " + m.group(i));
  15. System.out.println();
  16. }
  17.  
  18. public static void main(String[] args)
  19. {
  20. printMatch("^((\\+|00)(\\d{1,3})[\\s-]?)?(\\d{10})$", "+123-9854875847", 3, 4);
  21. printMatch("^(?:(?:\\+|00)(\\d{1,3})[\\s-]?)?(\\d{10})$", "+123-9854875847", 1, 2);
  22. // group not in match -> just prints 'null'
  23. printMatch("^(?:(?:\\+|00)(\\d{1,3})[\\s-]?)?(\\d{10})$", "9854875847", 1, 2);
  24. }
  25. }
  26.  
Success #stdin #stdout 0.07s 380160KB
stdin
Standard input is empty
stdout
String = +123-9854875847
Regex = ^((\+|00)(\d{1,3})[\s-]?)?(\d{10})$
Group 3 = 123
Group 4 = 9854875847

String = +123-9854875847
Regex = ^(?:(?:\+|00)(\d{1,3})[\s-]?)?(\d{10})$
Group 1 = 123
Group 2 = 9854875847

String = 9854875847
Regex = ^(?:(?:\+|00)(\d{1,3})[\s-]?)?(\d{10})$
Group 1 = null
Group 2 = 9854875847