使用Java正则检测字符串是否含SQL注入字符遇匹配问题
Hey there! Let's break down why your current regex isn't working as expected and get you a solution tailored exactly to your needs.
The Issue with Your Current Regex
Your [^a-zA-Z0-9] pattern matches all non-alphanumeric characters—that includes spaces, commas, exclamation marks, and way more than just the specific SQL injection-related characters you're targeting. Even worse, it misinterprets some of your intended target characters:
\bin regex is a word boundary anchor, not the literal backspace character you want to detect.- Characters like
\r,\n, and\taren't explicitly targeted, so your regex doesn't flag them even if they're present.
The Correct Regex for Your Target Characters
You need a regex that specifically matches these characters: ', ", backspace (\b), carriage return (\r), newline (\n), and tab (\t). Here's the properly escaped pattern to do that:
['"\\\b\r\n\t]
Pattern Breakdown:
['"]: Matches single or double quotes directly (no escape needed in most regex engines, but safe to keep as-is).\\\b: The double backslash escapes the first backslash so regex interprets it as a literal, turning\binto the actual backspace control character (instead of a word boundary).\r,\n,\t: Standard regex escape sequences for carriage return, newline, and tab control characters.
Example Usage (Python)
Here's how you'd implement this check in Python to verify if a string contains any of these high-risk characters:
import re def contains_sql_risk_chars(input_str): # Raw string notation (r'...') avoids extra escaping in Python strings pattern = r'[\'\"\\\b\r\n\t]' return re.search(pattern, input_str) is not None # Test cases print(contains_sql_risk_chars("User input with ' quote")) # Returns True print(contains_sql_risk_chars("Normal alphanumeric text")) # Returns False print(contains_sql_risk_chars("Input with\ttab character")) # Returns True
A Critical Note on SQL Injection Protection
While detecting these characters can help flag suspicious input, the only reliable way to prevent SQL injection is to use parameterized queries (prepared statements). Character blacklists can be bypassed by attackers using encoding or alternative syntax. Always prioritize parameterization over manual character checks for production code.
内容的提问来源于stack exchange,提问作者TechEnthu

