CodexBloom - Programming Q&A Platform

Regex for Validating Custom Usernames in Python - implementing Length and Special Characters

πŸ‘€ Views: 92 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-11
regex python validation Python

I'm collaborating on a project where I'm writing unit tests and I'm sure I'm missing something obvious here, but I'm trying to create a regular expression in Python that validates usernames for my web application. The username should be 5 to 15 characters long, can include letters (both uppercase and lowercase), digits, and the special characters `._-`. However, I also want to ensure that it does not start or end with a special character and want to have consecutive special characters. I've written the following regex: ```python import re username_pattern = r'^(?!.*[._-]{2})(?![._-])[A-Za-z0-9._-]{5,15}(?<![._-])$' ``` When I run this pattern, it seems to pass some usernames that shouldn't be valid, like `-_user123` or `validuser--`. I'm using Python 3.9 and the `re` module for regex operations. Here’s an example of how I’m testing this regex: ```python usernames_to_test = ['valid_user', 'invalid--user', 'user..name', '-user', 'user-', 'user123'] for username in usernames_to_test: if re.match(username_pattern, username): print(f'{username} is valid') else: print(f'{username} is invalid') ``` From my tests, `invalid--user` is showing up as valid, which it shouldn't. It's frustrating because I'm following what I believe are the correct rules for username validation. Can anyone guide to figure out what I'm missing or if there's a better way to structure this regex? I'm also considering performance implications for validating thousands of usernames at once, so any best practices would be appreciated. Any ideas what could be causing this? This is for a microservice running on CentOS. Thanks for your help in advance! Is this even possible? I've been using Python for about a year now. What's the best practice here? My development environment is Ubuntu 22.04.