You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Regex正则表达式优化需求:支持斜杠及带空格斜杠分隔单词

Optimized Regex for Your Requirements

Hey Mike, nice work on the original regex! Let's tweak it to support both space-separated and slash-separated words (including slashes with optional spaces on either side) while keeping your core rules intact.

Updated Regex

^(?=.{0,50}$)([A-Z][a-z]*(?:\s*/?\s*[A-Z][a-z]*)*)$

Breakdown of Changes

Let's walk through what's modified and why:

  • Length Check: The initial (?=.{0,50}$) stays exactly as is—this ensures your total string length never exceeds 50 characters.
  • Word Separator Flexibility: Replaced the strict space-only separator (+) with (?:\s*/?\s*). This pattern matches:
    • A single space ( )
    • A direct slash (/)
    • A slash with spaces on either side (/)
    • Any combination of optional spaces around a slash (like / or / )
  • Word Validation: The [A-Z][a-z]* pattern remains unchanged to enforce capitalized first letters followed by lowercase letters (or just a single capitalized letter for short words like "A" or "I").

Valid Test Cases

These will all pass the regex:

  • Jet Black (original space-separated format)
  • Jet/Black (direct slash separation)
  • Jet / Black (slash with surrounding spaces)
  • Hello/World Foo Bar (mixed separators, as long as total length ≤50)
  • Z (single capitalized letter, length 1)

Invalid Test Cases

These will fail (as expected):

  • jet Black (first word starts with lowercase)
  • Jet black (second word starts with lowercase)
  • Jet//Black (multiple consecutive slashes)
  • A very long string that definitely exceeds the fifty character limit here (over 50 characters)

Optional Strict Mode (If Needed)

If you want to restrict to only one type of separator (no mixing spaces and slashes), you can use this variation instead:

^(?=.{0,50}$)(?:([A-Z][a-z]* +)*[A-Z][a-z]*|([A-Z][a-z]*(?:\s*/\s*)+)[A-Z][a-z]*)$

This ensures all words are separated either by spaces or by slashes (with optional spaces around them), but not both in the same string.

内容的提问来源于stack exchange,提问作者Aligator3000

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:29:48