mfcss
mfcss

Reputation: 1511

Regex: How to match a range of characters except another range

I'm trying to create a regex filter to satisfy:
1) The 1st character should be a lower-case letter or a number
2) The rest of the characters should be a single character between index 32 and 126
3) However, none of the characters should be upper case letters or _

My current regex is: ^[a-z0-9][ -~]*$

This solves 1) and 2) above - but I struggle to include 3) above in the right way. Any help is appreciated.

Upvotes: 1

Views: 1016

Answers (1)

LukStorms
LukStorms

Reputation: 29647

A simple way is to add a negative lookahead for what you don't want.

^[a-z0-9](?!.*[A-Z_])[ -~]*$

But it's also possible to just split up the ranges, based on the ascii-table

^[a-z0-9][ -@\[-^`-~]*$

It's just a bit less easy to understand at a first glance.

Upvotes: 1

Related Questions