如何在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 likepythonare 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.
相关产品推荐
相关产品推荐

