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

如何在Django的urls.py中用URL匹配规则检测字符串中的连字符?

Solution for Validating URL Slug Strings with Hyphens

Hey there! Let's work through this regex problem for your URL-friendly strings. From your examples (python, python-django, python-django-admin), you need a pattern that matches valid slugs with hyphens, while avoiding messy invalid cases like leading/trailing hyphens or consecutive hyphens.

The Regex Pattern

Here's a regex that fits your exact needs:

^[a-z]+(?:-[a-z]+)*$

Breakdown of the Pattern

Let's break down each part so you understand exactly how it works:

  • ^ : Anchors the match to the start of the string (ensures no unwanted leading characters like hyphens)
  • [a-z]+ : Matches one or more lowercase letters (guarantees the slug starts with a letter, not a hyphen)
  • (?:-[a-z]+)* : A non-capturing group that matches a hyphen followed by one or more lowercase letters, repeated zero or more times. The * makes this part optional (so single-word slugs like python are allowed), and the non-capturing group (?:...) just groups the pattern without storing extra capture data.
  • $ : Anchors the match to the end of the string (stops trailing hyphens or random extra characters from slipping through)

Testing the Pattern

This regex will:

  • ✅ Match valid slugs: python, python-django, python-django-admin
  • ❌ Reject invalid cases:
    • -python (leading hyphen)
    • python- (trailing hyphen)
    • python--django (consecutive hyphens)
    • python_django (underscores instead of hyphens)
    • Python-Django (uppercase letters—adjust the regex to ^[a-zA-Z]+(?:-[a-zA-Z]+)*$ if you need to allow uppercase)

Optional Adjustments

If you want to allow numbers in your slugs (like python3-django), tweak the character set to include digits:

^[a-z0-9]+(?:-[a-z0-9]+)*$

内容的提问来源于stack exchange,提问作者Jay P.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:17:53