正则表达式以所有顺序查找字符串

时间:2014-05-10 10:50:15

标签: java regex

我有关于手机的推文列表和手机名称列表,现在我必须为每个手机名称计算。 我使用数组列表获取手机名称如下

brand_list.add("Samsung Galaxy S5");
brand_list.add("Nolia Lumia 525");

然后我有一个关于手机的推文列表 " RT @protectyrbubble:#PYBS5giveaway #WIN三星Galaxy S5。只需关注@protectyrbubble和RT!细节& T& Cs http://t.co/u0NTM00rhA ht ..."

然后我使用以下代码计算每部手机如下

for(int j=0;j<array_list.size();j++)
           {
              pattern = Pattern.compile(" ((.*)Samsung(.*)Galaxy(.*)S5(.*)",Pattern.CASE_INSENSITIVE) ;
                        matcher = pattern.matcher(array_list.get(j).toString());
                        while (matcher.find()) 
                        {

                              count++;

                        }
           }

在上面,array_list包含有关mobile的推文。现在,如果我使用上面的正则表达式,它适用于上面提到的推文,但它不适用于像

这样的字符串

&#34; Galaxy S5 Mini Sempat Nongol di Situs三星http://t.co/sinWiLpUNV&#34;

所以,我需要一个正则表达式,它也可以找到上面提到的推文。

提前致谢

1 个答案:

答案 0 :(得分:1)

您无法使用正则表达式检查订单。但似乎您只想知道字符串中是否包含字符串"Samsung""Galaxy""S5",因此您可以只询问3个匹配项:".*Samsung.*"".*Galaxy.*"".*S5.*"

String#contains()方法也是可能的,但遗憾的是它无法检查不区分大小写。

编辑:它可能与"(.*(Samsung|Galaxy|S5))*.*"类似,但我不确定正确的语法......也许你明白了。

如果您的手机名称在brand_list内,您可以这样做:

for(int j=0;j<array_list.size();j++)
{
    boolean allIn = true;
    for (String phoneName: brand_list)
    {
        String[] phoneWords = phoneName.split(" ");

        for (int wordIndex = 0; wordIndex < phoneWords.length; wordIndex++)
        {
            String regexPattern = "(.*)" + phoneWords[wordIndex] + "(.*)";
            pattern = Pattern.compile(regexPattern, Pattern.CASE_INSENSITIVE);
            matcher = pattern.matcher(array_list.get(j).toString());

            if (!matcher.find()) 
            {
                allIn = false;
            }
        }
    }
    System.out.println(allIn); // should be false here if one of the words
                               // couldn't be found in the strings and
                               // should be true otherwise
}