另一正则表达式需求:生成符合指定规则的正则表达式
Solution for Your Regex Requirements
Let's craft a regex that hits all three of your specified rules, with a clear breakdown so you understand exactly how each part works:
Final Regex
^(?=.*[A-Za-z])[A-Za-z0-9@'-][A-Za-z0-9@'-\s]*[A-Za-z0-9@'-]$
Component Breakdown
^&$: Anchor the regex to match the entire string (prevents partial matches from slipping through)(?=.*[A-Za-z]): Positive lookahead that guarantees the string includes at least one uppercase or lowercase letter[A-Za-z0-9@'-]: Matches the first character (can’t be a space, since space isn’t included here) — covers all allowed non-space characters[A-Za-z0-9@'-\s]*: Matches any number of allowed characters in the middle, including spaces (the\sadds space support,*means zero or more occurrences)[A-Za-z0-9@'-]: Matches the last character (also can’t be a space, same as the first character)
Valid & Invalid Examples
- Valid Strings:
Jane-SmithO'Neil 123admin@test-siteX(single letter, meets all rules)
- Invalid Strings:
Hello123(starts with space)Hello123(ends with space)123-@(no letters included)Hello!World(contains exclamation mark, not in allowed character set)
Quick Notes
- If you’re using this regex in a language that requires backslash escaping (like Java), you’ll need to double the backslash for
\s, making it\\s - The hyphen (
-) is placed at the end of the character set to avoid being interpreted as a range (e.g.,a-z), keeping it safe and readable
内容的提问来源于stack exchange,提问作者Ionut Cirja
相关产品推荐
相关产品推荐

