Это продолжение всех перекрывающихся подстрок, соответствующих регулярному выражению java.

Есть ли способ ускорить этот код?

public static void allMatches(String text, String regex)
  {
    for (int i = 0; i < text.length(); ++i) {
      for (int j = i + 1; j <= text.length(); ++j) {
        String positionSpecificPattern = "((?<=^.{"+i+"})("+regex+")(?=.{"+(text.length() - j)+"}$))";
        Matcher m = Pattern.compile(positionSpecificPattern).matcher(text);

        if (m.find()) 
        {   
          System.out.println("Match found: \"" + (m.group()) + "\" at position [" + i + ", " + j + ")");
        }   
      }   
    }   
  }
0
dsg 7 Июл 2012 в 04:43

1 ответ

Лучший ответ

В другом вопросе вы упомянули метод Matcher region(), но не использовали его в полной мере. Что делает его настолько ценным, так это то, что якоря будут совпадать на границах региона, как если бы они были границами отдельной строки. Предполагается, что у вас установлен параметр useAnchoringBounds(), но это настройка по умолчанию.

public static void allMatches(String text, String regex)
{
  Matcher m = Pattern.compile(regex).matcher(text);
  int end = text.length();
  for (int i = 0; i < end; ++i)
  {
    for (int j = i + 1; j <= end; ++j) 
    {
      m.region(i, j);

      if (m.find()) 
      {   
        System.out.printf("Match found: \"%s\" at position [%d, %d)%n",
                          m.group(), i, j);
      }   
    }   
  }   
}

Учитывая вашу примерную строку и регулярное выражение:

allMatches("String t = 04/31 412-555-1235;", "^\\d\\d+$");

... я получаю этот вывод:

Match found: "04" at position [11, 13)
Match found: "31" at position [14, 16)
Match found: "41" at position [17, 19)
Match found: "412" at position [17, 20)
Match found: "12" at position [18, 20)
Match found: "55" at position [21, 23)
Match found: "555" at position [21, 24)
Match found: "55" at position [22, 24)
Match found: "12" at position [25, 27)
Match found: "123" at position [25, 28)
Match found: "1235" at position [25, 29)
Match found: "23" at position [26, 28)
Match found: "235" at position [26, 29)
Match found: "35" at position [27, 29)
2
Alan Moore 7 Июл 2012 в 09:54
Потрясающе, большое спасибо! Да, я думаю, что добавление якорей ^ и $ поможет. Оказывается, для моих целей мне тоже нужен useTransparentBounds(true). Милая!
 – 
dsg
7 Июл 2012 в 10:15