正则表达式是验证和限制用户输入中特殊字符的有效工具。以下是几种常见场景的解决方案:
^[a-zA-Z0-9]+$
^[a-zA-Z0-9\s\-_@.]+$
(允许空格、连字符、下划线、@和点)
^[a-zA-Z0-9_\-.]{3,20}$
^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$
^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$
^[^';\"\\]+$
禁止单引号、分号、双引号和反斜杠
function validateInput(input, regexPattern) {
const regex = new RegExp(regexPattern);
return regex.test(input);
}
// 使用示例
const isValid = validateInput(userInput, '^[a-zA-Z0-9_\\-.]+$');
import re
def validate_input(input_str, pattern):
return bool(re.fullmatch(pattern, input_str))
# 使用示例
is_valid = validate_input(user_input, r'^[a-zA-Z0-9_\-\.]+$')
// 允许管理员配置允许的特殊字符
const allowedSpecialChars = '-_@.';
const regex = new RegExp(`^[a-zA-Z0-9${escapeRegExp(allowedSpecialChars)}]+$`);
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
通过合理使用这些正则表达式模式,您可以有效控制用户输入中的特殊字符,平衡安全性和用户体验。