fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6. import java.util.regex.*;
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. String[] lst = new String[] {"John Smith","John Smith (123)","John Smith (123) (456)"};
  13. Pattern p = Pattern.compile("(.+?)(?:\\s\\((\\d+)\\))?");
  14. for (String s: lst) {
  15. System.out.println("--- Next string ---");
  16. Matcher m = p.matcher(s);
  17. if (m.matches()) {
  18. System.out.println(m.group(1));
  19. if (m.group(2) != null)
  20. System.out.println(m.group(2));
  21. }
  22. }
  23. }
  24. }
Success #stdin #stdout 0.05s 711168KB
stdin
Standard input is empty
stdout
--- Next string ---
John Smith
--- Next string ---
John Smith
123
--- Next string ---
John Smith (123)
456