请求文件名正则校验方案:ASCII字符限制及禁用规则
Solution for Filename Regex Validation
Got it, let's break down how to build the correct regex for your filename validation requirements, then integrate it into your code.
Step 1: Clarify the Validation Rules
First, let's restate your rules to ensure we cover every edge case:
- Filename can only include ASCII characters from 32 (space) to 126 (~)
- Exclude these specific characters:
"(ASCII 34),’(ASCII 39),;(ASCII 59),<(ASCII 60),=(ASCII 61),>(ASCII 62),\(ASCII 92) - Filename must not contain the sequence
%00
Step 2: Build the Regex
Since JavaScript regex doesn't support character class intersections, we'll use a negated character class to exclude all disallowed characters (including non-printable ASCII chars outside 32-126) plus a negative lookahead to block the %00 sequence.
Here's the final regex:
/^(?!.*%00)[^\x00-\x1F\x7F\x22\x27\x3B\x3C\x3D\x3E\x5C]+$/
Let's break down each component:
^: Anchors the match to the start of the filename(?!.*%00): Negative lookahead that ensures the string never contains the%00sequence anywhere[^\x00-\x1F\x7F\x22\x27\x3B\x3C\x3D\x3E\x5C]+: Matches one or more characters that are not in this excluded list:\x00-\x1F: ASCII 0-31 (non-printable control characters)\x7F: ASCII 127 (DEL character)\x22: Double quote"\x27: Single quote’\x3B: Semicolon;\x3C: Less-than<\x3D: Equals=\x3E: Greater-than>\x5C: Backslash\
$: Anchors the match to the end of the filename
Step 3: Integrate into Your Code
Here's the complete working code with validation check:
let filename = "my_valid_file_123.txt"; let regex = /^(?!.*%00)[^\x00-\x1F\x7F\x22\x27\x3B\x3C\x3D\x3E\x5C]+$/; const isFilenameValid = regex.test(filename); console.log(`Filename: "${filename}"`); console.log(`Validation result: ${isFilenameValid ? "✅ Valid" : "❌ Invalid"}`);
Test Cases
Let's verify some examples:
- Valid filenames:
"document 123.pdf","test-file_$%^&*().txt","my notes.txt" - Invalid filenames:
"file\"name.txt"(contains backslash),"file%00broken.txt"(contains%00),"file<invalid>.txt"(contains<),"secret\file.txt"(contains backslash)
内容的提问来源于stack exchange,提问作者amitpowerpeace
相关产品推荐
相关产品推荐

