Heuristic:A616567126 GPT WEB JAVA Banned Word Regex Matching
| Knowledge Sources | |
|---|---|
| Domains | Security, Content_Moderation |
| Last Updated | 2026-10-13 18:00 GMT |
Overview
Use word-boundary regex matching (`\bword\b`) with case-insensitive lowercasing for banned word detection to prevent partial-match false positives.
Description
The `BannedPromptUtils` class checks Midjourney prompts against a list of banned words loaded from `/home/spring/config/banned-words.txt` (fallback: classpath `/banned-words.txt`). The banned word list contains 211 entries. The `isBanned` method converts the prompt to lowercase and uses `Pattern.compile("\\b" + bannedWord + "\\b")` to match each banned word with word boundaries. This ensures that a banned word like "kill" matches "kill" but not "killer" or "skill". The `checkBanned` method goes further: it finds the matched word's position in the original prompt and throws an exception with the exact matched substring, allowing the caller to show the user which specific word triggered the filter.
Usage
Use this heuristic when implementing banned word filtering for user-submitted prompts. Always use word-boundary regex (`\b`) to avoid false positives from substring matches. Lowercase the input before matching for case-insensitive comparison. Load the word list from an external file (not hardcoded) to allow updates without code changes.
The Insight (Rule of Thumb)
- Action: Use `Pattern.compile("\\b" + word + "\\b").matcher(prompt.toLowerCase()).find()` for each banned word.
- Value: Word boundary regex `\b` + lowercase conversion.
- Trade-off: Word boundary matching misses obfuscated words (e.g., "k.i.l.l", "killl"); however, it prevents false positives on legitimate words containing banned substrings.
- Compatibility: The banned words file is loaded once at class initialization (static block); changes require application restart.
Reasoning
Naive `String.contains()` matching would produce false positives: the banned word "war" would match "warning", "hardware", and "award". Word boundary regex (`\b`) ensures the banned word is matched only when it appears as a complete word, dramatically reducing false positives. Lowercasing the input before matching handles case variations ("Kill", "KILL", "kill") without needing case-insensitive regex flags. The external file loading with classpath fallback allows ops teams to update the banned word list by replacing the file at `/home/spring/config/banned-words.txt` without rebuilding the JAR.