fork download
  1. import java.util.regex.*;
  2. import java.util.ArrayList;
  3.  
  4. public class Main {
  5. private static Pattern combineRe(Pattern p1, Pattern p2){
  6. return Pattern.compile(combineRE(p1.pattern(), p2.pattern()));
  7. }
  8. private static String combineRE(String p1, String p2){
  9. return combineRE(p1, p2, true);
  10. }
  11. private static String combineRE(String p1, String p2, boolean anchors){
  12. int groups1 = 0, groups2=0;
  13. StringBuilder newP = new StringBuilder((anchors)?"^(?=":"(?=");
  14. newP.append(p1);
  15. if (anchors) newP.append('$');
  16. newP.append(")(?=");
  17.  
  18. Pattern capturingGroup = Pattern.compile("(?<!\\\\)(\\\\\\\\)*\\((?!\\?)");
  19. Matcher m = capturingGroup.matcher(p1);
  20. while(m.find()) groups1 ++;
  21.  
  22. m = capturingGroup.matcher(p2);
  23.  
  24. while(m.find()) groups2 ++;
  25. String new2 = p2;
  26.  
  27. for(int i=1; i<=groups2; i++)
  28. new2 = new2.replaceAll("(?<!\\\\)\\\\"+i, "\\\\" + (i+groups1));
  29.  
  30. newP.append(new2);
  31. if (anchors) newP.append('$');
  32. newP.append(')');
  33. if (anchors) newP.append(".*");
  34. return newP.toString();
  35. }
  36. private static String[] findAllCombinedRE(String p1, String p2, String haystack, boolean overlap){
  37. ArrayList<String> toReturn = new ArrayList<String>();
  38. Pattern pCombo = Pattern.compile(combineRE(p1,p2, false));
  39. String pComboMatch = combineRE(p1,p2, true);
  40. Matcher m = pCombo.matcher(haystack);
  41. int s = 0;
  42. while (m.find(s)){
  43. s = m.start()+1;
  44. String match = haystack.substring(m.start());
  45. for (int i=match.length(); i>0; i--){
  46. String sMatch = match.substring(0,i);
  47. if (Pattern.matches(pComboMatch, sMatch)){
  48. toReturn.add(sMatch);
  49. if (!overlap){
  50. s = m.start()+i;
  51. break;
  52. }
  53. }
  54. }
  55. }
  56. return toReturn.toArray(new String[]{});
  57.  
  58. }
  59. public static void main(String[] args){
  60. String p1 = "a.*";
  61. String p2 = ".*b";
  62. String p = combineRE(p1, p2);
  63. String s = "caabcbc";
  64. System.out.println("p1: " + p1 + "\np2: " + p2 + "\np: " + p + "\ns: " + s);
  65. Matcher m = Pattern.compile(p).matcher(s);
  66. m = Pattern.compile("(?=4)").matcher("01234567890123456");
  67. String[] noverlap = findAllCombinedRE(p1, p2, s, false);
  68. for (int i=0; i<noverlap.length; i++){
  69. System.out.println(noverlap[i]);
  70. }
  71. System.out.println();
  72. String[] overlap = findAllCombinedRE(p1, p2, s, true);
  73. for (int i=0; i<overlap.length; i++){
  74. System.out.println(overlap[i]);
  75. }
  76. }
  77. }
Success #stdin #stdout 0.07s 380224KB
stdin
Standard input is empty
stdout
p1: a.*
p2: .*b
p: ^(?=a.*$)(?=.*b$).*
s: caabcbc
aabcb

aabcb
aab
abcb
ab