正则表达式需求:仅允许%&且需2个及以上,禁止其他特殊字符
Solution
Got it, let's break down your requirements and build the exact regex you need. First, let's restate your rules clearly to make sure we're on the same page:
- Your string can only contain the special characters
%and&— any other character (like@,$, letters, numbers, or other symbols) should make validation fail - The string must have 2 or more total instances of
%and/or&(so no single%, single&, or empty strings allowed)
The Regex You Need
^[%&]{2,}$
How This Regex Works
Let's break down each component so you understand exactly what it's doing:
^: Anchors the match to the start of the string — this makes sure there aren't any hidden, invalid characters before your allowed ones[%&]: A character class that matches only a%or a&— this automatically excludes every other character by default{2,}: A quantifier that requires the preceding character class to appear at least 2 times — this enforces your "2+ special characters" rule$: Anchors the match to the end of the string — this ensures there aren't any invalid characters hiding after your allowed ones
Test Cases to Verify
Valid (Matches Successfully)
%%&&%&&%%%&%&
Invalid (Fails Validation)
%(only 1 special character)&(only 1 special character)%@(contains forbidden@)$&(contains forbidden$)abc%(includes letters)- Empty string (no special characters at all)
Why This Is Better Than Your Original Regex
Your original regex ^((%&)*(?!@).)*$ allowed zero or more %/& and blocked @, but it still let other characters slip through thanks to the . wildcard (which matches any character). This new regex tightens things up to only allow % and &, and enforces the minimum count requirement you need.
内容的提问来源于stack exchange,提问作者Delfin




