fork download
  1. import java.util.*;
  2. import java.util.regex.*;
  3. import java.lang.*;
  4. import java.io.*;
  5.  
  6. class Ideone
  7. {
  8. public static void main (String[] args) throws java.lang.Exception
  9. {
  10. String[] phrases = new String[2];
  11. phrases[0] = "student (male)";
  12. phrases[1] = "worker (female)";
  13.  
  14. Pattern[] ptn = new Pattern[phrases.length];
  15.  
  16. int i = 0;
  17. for (String p : phrases)
  18. {
  19. p = p.replaceAll("\\(", "\\\\(");
  20. p = p.replaceAll("\\)", "\\\\)");
  21. String regex = p+"\\:\\s\\w+";
  22. System.out.println("regex: " + regex);
  23. ptn[i] = Pattern.compile(regex);
  24. i++;
  25. }
  26.  
  27. String text = "student (male): John";
  28.  
  29. for(Pattern p : ptn)
  30. {
  31. Matcher m = p.matcher(text);
  32. System.out.println("matcher: " + m);
  33. while(m.find())
  34. {
  35. System.out.println("group: " + m.group());
  36. }
  37. }
  38. }
  39. }
Success #stdin #stdout 0.07s 380224KB
stdin
Standard input is empty
stdout
regex: student \(male\)\:\s\w+
regex: worker \(female\)\:\s\w+
matcher: java.util.regex.Matcher[pattern=student \(male\)\:\s\w+ region=0,20 lastmatch=]
group: student (male): John
matcher: java.util.regex.Matcher[pattern=worker \(female\)\:\s\w+ region=0,20 lastmatch=]