Regex - how to exclude single word?

后端 未结 3 738
再見小時候
再見小時候 2020-12-07 23:13

I am using http://www.position-absolute.com/articles/jquery-form-validator-because-form-validation-is-a-mess/ for validation. Validation rules are defined in a following way

相关标签:
3条回答
  • 2020-12-07 23:31

    This is a good time to use word boundary assertions, like @FailedDev indicated, but care needs to be exercised to avoid rejecting certain not-TOO-special cases, such as wordy, wordsmith or even not so obviously cases like sword or foreword

    I believe this will work pretty well:

    \b(?!\bword\b)\w+\b
    

    This is the expression broken down:

    \b        # assert at a word boundary
    (?!       # look ahead and assert that what follows IS NOT... 
      \b      #   a word boundary
      word    #   followed by the exact characters `word`
      \b      #   followed by a word boundary
    )         # end look-ahead assertion
    \w+       # match one or more word characters: `[a-zA-Z0-9_]`
    \b        # then a word boundary
    

    The expression in the original question, however, matches more than word characters. [a-zA-Z\ \']+ matches spaces (to support multiple words in the input) and single quotes as well (for apostrophes?). If you need to allow words with apostrophes in them then use the following expression:

    \b(?!\bword\b)[a-zA-Z']+\b
    

    RegexBuddy test to exclude a 'word' from matching

    0 讨论(0)
  • 2020-12-07 23:33
    \b(?:(?!word)\w)+\b
    

    Will not match the "word".

    0 讨论(0)
  • 2020-12-07 23:52

    It's unclear from your question what you want, but I've interpreted it as "not matching input that contains a particular word". The regex for this is:

    ^(?!.*\bexclude_word\b)
    
    0 讨论(0)
提交回复
热议问题