正则表达式可用于验证字符串不包含一组单词.这是一个经过测试的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那样有效.
| 归档时间: |
|
| 查看次数: |
3208 次 |
| 最近记录: |