Regular expression to match all search terms

后端 未结 3 413
逝去的感伤
逝去的感伤 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 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
    

提交回复
热议问题