正则表达式作为if-else条件返回意外结果,求正确的1-2位字符验证正则
Got it, let's work through this problem step by step. Your current regex only matches 1-2 digit numbers, which is why it's failing for the letter-based values you need to accept. Let's build a solution that covers all your requirements and is easy to extend later.
First, Clarify the Exact Requirements
We need to return true only if the input:
- Is a string with 1 or 2 characters exactly
- Falls into one of two categories:
- Specific letter combinations:
P,M,G,S,L,PP,GG,XS,XL(case-insensitive? Your examples use uppercase, but we'll add support for lowercase if needed) - Numbers between 30 and 50 (inclusive)
- Specific letter combinations:
The Corrected Regular Expression
Here's a regex that covers all these cases:
/^(?:[PMGSXL]|PP|GG|XS|XL|3[0-9]|4[0-9]|50)$/i
Let's break down what each part does:
^and$: Ensure the entire input string is matched (so partial matches likePP1orXSLget rejected)[PMGSXL]: Matches any single valid letter (P, M, G, S, X, L)PP|GG|XS|XL: Matches the valid 2-letter combinations3[0-9]: Matches numbers 30-394[0-9]: Matches numbers 40-4950: Explicitly matches the number 50iflag: Makes the match case-insensitive (remove this if you need strict uppercase matching)(?:...): A non-capturing group to wrap all options—this is just for efficiency, no functional impact here
Example Function Implementation
Wrap this regex in a function to handle input validation properly (we'll also add a check to ensure the input is a string first):
function isValidParam(input) { // Reject non-string inputs immediately if (typeof input !== 'string') { return false; } const validationRegex = /^(?:[PMGSXL]|PP|GG|XS|XL|3[0-9]|4[0-9]|50)$/i; return validationRegex.test(input); }
Test Cases to Verify
Let's test some common inputs to confirm it works:
isValidParam('PP')→trueisValidParam('g')→true(thanks to theiflag)isValidParam('50')→trueisValidParam('29')→false(below 30)isValidParam('XL')→trueisValidParam('XXX')→false(too long)isValidParam('51')→false(above 50)isValidParam('S')→true
Why Your Original Regex Failed
Your original regex /^[0-9]{1,2}$/gi has two key limitations:
- It only matches digits—so all letter-based values (like
PPorM) get rejected, which is why you saw unexpected results. - It doesn't restrict numbers to the 30-50 range—so values like
10or55would incorrectly returntrue.
How to Extend Later
If you need to add more valid values down the line:
- For single letters: Add them to the
[PMGSXL]character group (e.g., addR→[PMGSXLR]) - For 2-letter combinations: Add a new option with
|(e.g., addXXwould be|XX) - For numbers: Adjust the number range (e.g., add 51-55 → change the number part to
3[0-9]|4[0-9]|5[0-5])
内容的提问来源于stack exchange,提问作者almostamachine

