简体   繁体   中英

Can someone help me with writing a regular expression?

I'm making a search function for my app and I need a good regular expression. Right now, when the user searches "RAC" (it's a band name), it returns all of my posts that have the letters "rac" in the title. This, however, is a bit broken and can only be fixed by a regular expression. I will provide some examples and say whether or not they should be included.

  1. Sir Sly - Miracle : DON'T INCLUDE
  2. RAC - Let Go : INCLUDE
  3. Amtrac - Walkin' : DON'T INCLUDE
  4. Bastille - Laura Palmer (RAC Remix) : INCLUDE
  5. Cold War Kids - Miracle Mile : DON'T INCLUDE
  6. MNDR - Feed Me Diamons (ft. RAC) : INCLUDE

Does anyone have a good regular expression that could help me out? PS you can test your regular expression here .

Edit: this is a solution for Java - if not the intended language, please refine your tags

You can use word boundaries for this, and a case-sensitive Pattern , as such:

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());
}

Output

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

There's many tools that can help you instead of rolling your own solution. Have you considered Lucene

Similar solution... but more efficient
in order to avoid to allocate useless objects

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM