Reputation: 814
Let's say I have this:
[a-zA-Z0-9., -&:]+
which allows alphanumeric letters and some special chars (comma, dot, dash, etc), for one or more times. But now, I want to only allow those special chars when there are also alphanumeric letters:
a-b, c
: ok
.a:
: ok
,-.
: NOT ok
,
: NOT ok
I tried a few things, but still couldn't figure out a way of doing it. How do I do that?
Upvotes: 1
Views: 995
Reputation: 3215
Pure regex solutions proposed above are obviously good, but I'm not sure if I'd be happy to find one of those in the code. People already find regex tricky and contextual logic makes it even trickier. At the same time, it can be easily divided into two problems and solved in the code :)
const allCharsRegex = /^[a-zA-Z0-9 !@#$%^&*()-_-~.+,/\" ]+$/g;
const alphaNumericRegex = /[a-zA-Z0-9]+/g;
let charactersMatch = text.match(allCharsRegex);
let anyAlphanumeric = text.match(alphaNumericRegex );
return charactersMatch && anyAlphanumeric;
IMO that's more readable and flexible.
Upvotes: 0
Reputation: 882806
If you want to ensure there's at least one alphanumeric character in there, you can just use:
[a-zA-Z0-9., &:-]*[a-zA-Z0-9][a-zA-Z0-9., &:-]*
This is basically zero or more of your current pattern (slightly modified(a)), followed by one alphanumeric, followed by zero or more of your current pattern again. This guarantees no match unless the string has one or more alphanumerics.
You may also want to consider putting the ^
and $
markers at the ends of your pattern if you using a regex function that allows partial matching. Without that, you could match something like <some-invalid-character>A
. This may not be necessary if you're using a "full match" function.
(a) The modification, as per comments in another answer, is to move the -
to the end of the regex to have it treated as a literal hyphen rather than a character range.
Upvotes: 3
Reputation: 522817
I would use an alternation here:
^(?=.*[A-Za-z0-9])[a-zA-Z0-9., &:-]+$
This regex reads quite close to your requirements, and says to match:
^ from the start of the string
(?=.*[A-Za-z0-9]) assert that at least one alphanumeric character be present
[a-zA-Z0-9., &:-]+ if so, then match either alphas or certain symbols
$ end of the string
Side note: Note carefully that in your original character class, you placed dash in the middle somewhere:
[a-zA-Z0-9., -&:]+
This actually defines a range of characters in between space character and &
; the hyphen character is not being included. You can see in my regex that I have moved dash to the end of the class, to be sure that it gets included as a literal.
Upvotes: 2