Jack
Jack

Reputation: 23

Regex to check if a string contains at least A-Za-z0-9 but not an &

I am trying to check if a string contains at least A-Za-z0-9 but not an &. My experience with regexes is limited, so I started with the easy part and got:

.*[a-zA-Z0-9].*

However I am having troubling combining this with the does not contain an & portion. I was thinking along the lines of ^(?=.*[a-zA-Z0-9].*)(?![&()]).* but that does not seem to do the trick.

Any help would be appreciated.

Upvotes: 2

Views: 744

Answers (1)

Jakub Wasilewski
Jakub Wasilewski

Reputation: 2976

I'm not sure if this what you meant, but here is a regular expression that will match any string that:

  • contains at least one alpha-numeric character
  • does not contain a &

This expression ensures that the entire string is always matched (the ^ and $ at beginning and end), and that none of the characters matched are a "&" sign (the [^&]* sections):

^[^&]*[a-zA-Z0-9][^&]*$

However, it might be clearer in code to simply perform two checks, if you are not limited to a single expression.

Also, check out the \w class in regular expressions (it might be the better solution for catching alphanumeric chars if you want to allow non-ASCII characters).

Upvotes: 1

Related Questions