fork download
  1. import java.util.regex.*;
  2.  
  3. public class Main {
  4. private static Pattern combineRe(Pattern p1, Pattern p2){
  5. return Pattern.compile(combineRE(p1.pattern(), p2.pattern()));
  6. }
  7. private static String combineRE(String p1, String p2){
  8. int groups1 = 0, groups2=0;
  9. StringBuilder newP = new StringBuilder("(?=");
  10. newP.append(p1);
  11. newP.append("$)(?=");
  12.  
  13. Pattern capturingGroup = Pattern.compile("(?<!\\\\)(\\\\\\\\)*\\((?!\\?)");
  14. Matcher m = capturingGroup.matcher(p1);
  15. while(m.find()) groups1 ++;
  16.  
  17. m = capturingGroup.matcher(p2);
  18.  
  19. while(m.find()) groups2 ++;
  20. String new2 = p2;
  21.  
  22. for(int i=1; i<=groups2; i++)
  23. new2 = new2.replaceAll("(?<!\\\\)\\\\"+i, "\\\\" + (i+groups1));
  24.  
  25. newP.append(new2);
  26. newP.append(").*");
  27. return newP.toString();
  28. }
  29. public static void main(String[] args){
  30. String p1 = "a.*";
  31. String p2 = ".*b";
  32. String p = combineRE(p1, p2);
  33. String s = "cacbc";
  34. System.out.println("p1: " + p1 + "\np2: " + p2 + "\np: " + p + "\ns: " + s);
  35. Matcher m = Pattern.compile(p).matcher(s);
  36. int i = 0;
  37. while (m.find()) {
  38. System.out.println("find result " + (++i) + ": " + m.group());
  39. }
  40. }
  41. }
Success #stdin #stdout 0.06s 380224KB
stdin
"a.*" ".*b" "cacbc"
stdout
p1: a.*
p2: .*b
p: (?=a.*$)(?=.*b).*
s: cacbc
find result 1: acbc