正则表达式不匹配一组字符串

gre*_*reg 2 java regex

如何构造一个不包含一组字符串的正则表达式.

对于此示例,我想验证地址行1文本框,以便它不包含任何辅助地址部分,如'Apt','Bldg','Ste','Unit'等.

rid*_*ner 5

正则表达式可用于验证字符串不包含一组单词.这是一个经过测试的Java代码片段,带有注释的正则表达式,它正是这样做的:

if (s.matches("(?sxi)" +
    "# Match string containing no 'bad' words.\n" +
    "^                # Anchor to start of string.\n" +
    "(?:              # Step through string one char at a time.\n" +
    "  (?!            # Negative lookahead to exclude words.\n" +
    "    \\b          # All bad words begin on a word boundary\n" +
    "    (?:          # List of 'bad' words NOT to be matched.\n" +
    "      Apt        # Cannot be 'Apt',\n" +
    "    | Bldg       # or 'Bldg',\n" +
    "    | Ste        # or 'Ste',\n" +
    "    | Unit       # or 'Unit'.\n" +
    "    )            # End list of words NOT to be matched.\n" +
    "    \\b          # All bad words end on a word boundary\n" +
    "  )              # Not at the beginning of bad word.\n" +
    "  .              # Ok. Safe to match this character.\n" +
    ")*               # Zero or more 'not-start-of-bad-word' chars.\n" +
    "$                # Anchor to end of string.")
    ) {
    // String has no bad words.
    System.out.print("OK: String has no bad words.\n");
} else {
    // String has bad words.
    System.out.print("ERR: String has bad words.\n");
} 
Run Code Online (Sandbox Code Playgroud)

这假定单词必须是"整个"单词,并且无论如何都应该识别"坏"单词.另请注意,(正如其他人已正确说明的那样),这不如仅仅检查坏词的存在然后采用逻辑NOT那样有效.