为JSON Schema优化正则表达式:匹配合规的含重音字符字符串
Optimized Regex for Your JSON Schema Constraints
Hey there! Let's fix your regex problem while checking all your boxes—no more awkward three-group structure, proper首尾 character restrictions, and no consecutive spaces or hyphens. Here's how to do it step by step:
Core Regex Solution
First, here's the optimized regex that meets all your requirements:
^(?=.{0,100}$)(?:(?!Ð×Þß÷þø)[A-Za-zÀ-ÿŒœ](?:[' -](?!Ð×Þß÷þø)[A-Za-zÀ-ÿŒœ])*)?$
Breakdown of Each Part
Let's walk through this so you understand exactly how it works:
- Length Control:
(?=.{0,100}$)- This positive lookahead ensures the entire string is between 0 and 100 characters long, satisfying your first constraint.
- Empty String Allowance: The outer
(?:...)?makes the entire non-empty pattern optional, so empty strings are valid. - Valid Start/End Characters:
- The pattern starts with
(?!Ð×Þß÷þø)[A-Za-zÀ-ÿŒœ]: this matches a valid letter or accented character (includingœ, excluding the forbidden Greek/special characters you listed). This immediately blocks spaces, single quotes, or hyphens from appearing at the start.
- The pattern starts with
- Internal Separators (No Consecutive Ones!):
- The
(?:[' -](?!Ð×Þß÷þø)[A-Za-zÀ-ÿŒœ])*part allows any number of "separator + valid character" pairs.- Separators (space,
',-) can only appear between two valid characters, so they'll never end up at the string's tail. - Since each separator must be followed by a valid character, consecutive separators (like
--,, or-) are automatically blocked—no extra checks needed!
- Separators (space,
- The
Test Cases to Validate
Let's confirm this works for common scenarios:
- Valid: Empty string,
"Élodie","Jean-Luc","O'Neil","Marie Claire", a 100-character valid string - Invalid:
" -Test"(starts with separators),"Test-"(ends with hyphen),"Test "(ends with spaces),"Test--Name"(consecutive hyphens),"Ðavid"(contains forbidden character), 101-character string
JSON Schema Integration
When using this in a JSON Schema, remember to escape backslashes if your tooling requires it. Here's what that looks like:
{ "type": "string", "pattern": "^(?=.{0,100}$)(?:(?!Ð×Þß÷þø)[A-Za-zÀ-ÿŒœ](?:[' -](?!Ð×Þß÷þø)[A-Za-zÀ-ÿŒœ])*)?$" }
内容的提问来源于stack exchange,提问作者Will59
相关产品推荐
相关产品推荐

