有人可以帮我写正则表达式吗?

时间:2014-02-26 08:45:03

标签: java javascript android html regex

我正在为我的应用程序制作搜索功能,我需要一个很好的正则表达式。现在,当用户搜索“RAC”(它是一个乐队名称)时,它会返回标题中包含字母“rac”的所有帖子。但是,这有点破碎,只能通过正则表达式修复。我将提供一些例子并说明是否应将它们包括在内。

  1. Sir Sly - 奇迹:不要包括
  2. RAC - Let Go:INCLUDE
  3. Amtrac - Walkin':不包括
  4. Bastille - Laura Palmer(RAC Remix):INCLUDE
  5. 冷战儿童 - Miracle Mile:不包括
  6. MNDR - Feed Me Diamons(英尺RAC):INCLUDE
  7. 有没有人有一个很好的正则表达式可以帮助我?附:你可以测试你的正则表达式here

3 个答案:

答案 0 :(得分:3)

编辑:这是Java的解决方案 - 如果不是目标语言,请优化标记

您可以为此使用单词边界,并使用区分大小写的Pattern,如下所示:

String[] inputs = {"Sir Sly - Miracle",// : DON'T INCLUDE
        "RAC - Let Go",// : INCLUDE
        "Amtrac - Walkin'",// : DON'T INCLUDE
        "Bastille - Laura Palmer (RAC Remix)",// : INCLUDE
        "Cold War Kids - Miracle Mile",// : DON'T INCLUDE
        "MNDR - Feed Me Diamons (ft. RAC)"// : INCLUDE
        };
Pattern p = Pattern.compile("\\bRAC\\b");
for (String input: inputs) {
    Matcher m = p.matcher(input);
    System.out.printf("%s --> found ? %b%n", input, m.find());
}

<强>输出

Sir Sly - Miracle --> found ? false
RAC - Let Go --> found ? true
Amtrac - Walkin' --> found ? false
Bastille - Laura Palmer (RAC Remix) --> found ? true
Cold War Kids - Miracle Mile --> found ? false
MNDR - Feed Me Diamons (ft. RAC) --> found ? true

答案 1 :(得分:0)

有许多工具可以帮助您而不是滚动您自己的解决方案。您考虑过Lucene

了吗?

答案 2 :(得分:-1)

类似的解决方案......但效率更高
以避免分配无用的对象

String[] bands =  {"Sir Sly - Miracle",// : DON'T INCLUDE
                   "RAC - Let Go",// : INCLUDE
                   "Amtrac - Walkin'",// : DON'T INCLUDE
                   "Bastille - Laura Palmer (RAC Remix)",// : INCLUDE
                   "Cold War Kids - Miracle Mile",// : DON'T INCLUDE
                   "MNDR - Feed Me Diamons (ft. RAC)",// : INCLUDE
};

for(String s : bands){
    if(Pattern.matches(".*(RAC).*", s))
            System.out.printf("%s\n",s);
}