JS正则表达式求助:限制点号首尾位置及重复等规则实现
Solution for Your Regex Requirement
Hey there! Let's fix this regex step by step. First, let's recap your exact requirements to make sure we cover everything:
- Allowed characters: uppercase/lowercase letters, numbers,
! # $ % & ' * + - / = ? ^ _{ | } ~`, and dots (`.`) - Dots can't be at the start or end of the string
- Dots can't appear consecutively
Why Your Current Regex Isn't Working
Your attempt /^[^.]([\^><@,.]+)/ has a few key issues:
- It includes characters like
^,>,<,@,,that aren't in your allowed list - It doesn't enforce the "no consecutive dots" rule or prevent dots from appearing at the end of the string
- It only matches the start of the string, not the entire input (missing the
$anchor to lock the end)
The Correct Regex
Here's a regex that meets all your requirements perfectly:
^[A-Za-z0-9!#$%&'*+\-/=?^_`{|}~](?:\.?[A-Za-z0-9!#$%&'*+\-/=?^_`{|}~])*$
Breakdown of the Regex
Let's break this down piece by piece so you understand exactly how it enforces your rules:
^: Anchors the match to the start of the string (ensures we don't match partial inputs)[A-Za-z0-9!#$%&'*+\-/=?^_{|}~]`: Matches the first character, which must be a non-dot allowed character (solves the "no dot at start" rule)(?:...): A non-capturing group (we don't need to save this part separately) that repeats zero or more times:\.?: An optional dot (if present)[A-Za-z0-9!#$%&'*+\-/=?^_{|}~]`: Immediately follows any dot, ensuring the dot is never followed by another dot (solves the "no consecutive dots" rule)
$: Anchors the match to the end of the string, ensuring the last character is always a non-dot allowed character (solves the "no dot at end" rule)
Test Cases to Verify
- ✅ Valid:
Test123!$,a.b.c,user.name_123~ - ❌ Invalid:
.startWithDot,endWithDot.,double..dots,invalid@char
内容的提问来源于stack exchange,提问作者Vivek
相关产品推荐
相关产品推荐

