Regular expression to match all search terms

后端 未结 3 414
逝去的感伤
逝去的感伤 2021-01-25 00:47

I need a regular expression that will match on all terms in a set of search terms. If the user types \"bat sun\" then I need to match any text entries that have words starting w

相关标签:
3条回答
  • 2021-01-25 00:59

    Probably a regex like below if you really want to use regex:

    (?=.*\bsun)(?=.*\bbat).*
    

    Of course you want to make it ignore case.

    0 讨论(0)
  • 2021-01-25 01:04

    Depending on your definition of "word", you might be able to get away with using \b to match the beginning of a word.

    As for checking for two results, it's much easier to do using two matches.

    /\bsun/i && /\bbat/i          # Engines without implicit anchoring
    /.*\bsun.*/i && /.*\bbat.*/i  # Engines with implicit anchoring
    

    It can be done if your regex engine supports zero-width lookaheads.

    /^(?=.*\bsun)(?=.*\bbat)/si   # Engines without implicit anchoring
    /^(?=.*\bsun).*\bbat/si       # Engines without implicit anchoring
    /(?=.*\bsun)(?=.*\bbat).*/si  # Engines with implicit anchoring
    
    0 讨论(0)
  • 2021-01-25 01:20

    I think you can do something along the lines of:

    .find( { Item: { $regex : /\b[Term1]/i, $regex : /\b[Term2]/i, $regex : /\b[TermN]/i } } );

    See: http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-RegularExpressions

    0 讨论(0)
提交回复
热议问题