шаблон для следующего условия в Java - PullRequest
0 голосов
/ 29 мая 2010

Я хочу знать, как написать шаблон ..

например:

слово

   "AboutGoogle AdWords Drive traffic and customers to your site. Pay through Cheque,      Net Banking or Credit Card. Google Toolbar Add a search box to your browser. Google SMS To find out local information simply SMS to 54664. Gmail Free email with 7.2GB storage and less spam. Try Gmail today. Our ProductsHelp Help with Google Search, Services and ProductsGoogle Web Search Features Translation, I'm Feeling Lucky, CachedGoogle Services & Tools Toolbar, Google Web APIs, ButtonsGoogle Labs Ideas, Demos, ExperimentsFor Site OwnersAdvertising AdWords, AdSenseBusiness Solutions Google Search Appliance, Google Mini, WebSearchWebmaster Central One-stop shop for comprehensive info about how Google crawls and indexes websitesSubmit your content to Google Add your site, Google SitemapsOur CompanyPress Center News, Images, ZeitgeistJobs at Google Openings, Perks, CultureCorporate Info Company overview, Philosophy, Diversity, AddressesInvestor Relations Financial info, Corporate governanceMore GoogleContact Us FAQs, Feedback, NewsletterGoogle Logos Official Logos, Holiday Logos, Fan LogosGoogle Blog Insights to Google products and cultureGoogle Store Pens, Shirts, Lava lamps©2010 Google - Privacy Policy - Terms of Service"

Мне нужно найти какое-нибудь слово ...

например "Google Insights"

так как написать код в Java ...

Я просто пишу маленький код ...

проверь мой код и ответь на мой вопрос ...

этот код используется только для поиска искомого слова, где это.

но мне нужно отобразить некоторые слова в начале поискового слова и отобразить некоторые слова в задней части поиска ...

похоже на поиск в Google ...

мой код

Pattern p = Pattern.compile("(?i)(.*?)"+search+"");
Matcher m = p.matcher(full);
String title="";
while (m.find() == true) 
{
  title=m.group(1);
  System.out.println(title);
} 

полное оригинальное содержание, поиск с поисковым словом ...

спасибо и заранее

Ответы [ 3 ]

1 голос
/ 29 мая 2010

Регулярные выражения нельзя использовать ни для чего, они мощные, но даже регулярные выражения имеют свои ограничения. Код ниже ищет конкретное слово:

    public static void main(String[] args)
    {
        String str = "AboutGoogle AdWords Drive traffic and customers to your site. Pay through Cheque,      Net Banking or Credit Card. Google Toolbar Add a search box to your browser. Google SMS To find out local information simply SMS to 54664. Gmail Free email with 7.2GB storage and less spam. Try Gmail today. Our ProductsHelp Help with Google Search, Services and ProductsGoogle Web Search Features Translation, I'm Feeling Lucky, CachedGoogle Services & Tools Toolbar, Google Web APIs, ButtonsGoogle Labs Ideas, Demos, ExperimentsFor Site OwnersAdvertising AdWords, AdSenseBusiness Solutions Google Search Appliance, Google Mini, WebSearchWebmaster Central One-stop shop for comprehensive info about how Google crawls and indexes websitesSubmit your content to Google Add your site, Google SitemapsOur CompanyPress Center News, Images, ZeitgeistJobs at Google Openings, Perks, CultureCorporate Info Company overview, Philosophy, Diversity, AddressesInvestor Relations Financial info, Corporate governanceMore GoogleContact Us FAQs, Feedback, NewsletterGoogle Logos Official Logos, Holiday Logos, Fan LogosGoogle Blog Insights to Google products and cultureGoogle Store Pens, Shirts, Lava lamps©2010 Google - Privacy Policy - Terms of Service";
        String searchWord = "your";

        int loc = 0;
        loc = str.indexOf(searchWord);
        while (loc != -1)
        {
            loc = str.indexOf(searchWord, loc + searchWord.length());
            System.out.println("found");
        }
    }

Следующий вывод:

найдено

найдено

найдено

обнаруж

Надеюсь, это поможет.

1 голос
/ 29 мая 2010

Лучшее решение - использовать действительно сложные алгоритмы поиска и индексации строк. Если вы не заботитесь о производительности, то что-то вроде этого довольно легко реализовать:

import java.util.*;
public class SearchAndContext {
    public static void main(String[] args) {
        String text = "The path of the righteous man is beset on all sides by "
        + "the iniquities of the selfish and the tyranny of evil men. Blessed "
        + "is he, who in the name of charity and good will, shepherds the "
        + "weak through the valley of darkness, for he is truly his brother's "
        + "keeper and the finder of lost children. And I will strike down "
        + "upon thee with great vengeance and furious anger those who would "
        + "attempt to poison and destroy my brothers. And you will know my "
        + "name is the Lord when I lay my vengeance upon thee.";

        List<String> words = Arrays.asList(text.split(" "));
        final int W = 3;
        final int N = words.size();
        String[] queries = { "vengeance", "and", "monkeys" };
        for (String query : queries) {
            List<String> search = words;
            System.out.println("Searching for " + query);
            for (int idx = -1, pos; (pos = search.indexOf(query)) != -1; ) {
                idx += (pos+1);
                int left = Math.max(0, idx - W);
                int right = Math.min(N, idx + W + 1);
                System.out.println(words.subList(left, right));
                search = search.subList(pos+1, search.size());
            }
        }
    }
}

Это печатает:

Searching for vengeance
[thee, with, great, vengeance, and, furious, anger]
[I, lay, my, vengeance, upon, thee.]
Searching for and
[of, the, selfish, and, the, tyranny, of]
[name, of, charity, and, good, will,, shepherds]
[his, brother's, keeper, and, the, finder, of]
[with, great, vengeance, and, furious, anger, those]
[attempt, to, poison, and, destroy, my, brothers.]
Searching for monkeys

Как вы можете видеть, это находит вхождения поискового запроса, а также обеспечивает контекст до W=3 слов вокруг "удара".

API ссылки

0 голосов
/ 29 мая 2010

Шаблоны замечены, а не созданы. Для существования шаблона вы должны заметить, что ряд проблем решается аналогичным образом.

Как только вы видите, что одна и та же структура кода повторяется снова и снова, вы нашли шаблон. Если вы задокументируете структуру кода и отметите его сильные стороны в решении проблемы и его слабые стороны в решении проблемы, то вы будете задокументировать шаблон. Документирование шаблона упрощает его использование другими и упрощает повторное использование шаблона позже.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...