Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to allow alphanumeric, spaces, some special characters

I have this ^[a-zA-Z0-9 @&$]*$, but not working for me in few cases.

If someone types

  • A string that only consists of digits (e.g. 1234567)
  • A string starting with a special character (e.g. &123abc)

need to be rejected. Note that a special char can be in the middle and at the end.

like image 819
Sharpeye500 Avatar asked Oct 18 '25 21:10

Sharpeye500


2 Answers

You seem to need to avoid matching strings that only consist of digits and make sure the strings start with an alphanumeric. I assume you also need to be able to match empty strings (the original regex matches empty strings).

That is why I suggest

^(?!\d+$)(?:[a-zA-Z0-9][a-zA-Z0-9 @&$]*)?$

See the regex demo

Details

  • ^ - start of string
  • (?!\d+$) - the negative lookahead that fails the match if a string is numeric only
  • (?:[a-zA-Z0-9][a-zA-Z0-9 @&$]*)? - an optional sequence of:
    • [a-zA-Z0-9] - a digit or a letter
    • [a-zA-Z0-9 @&$]* - 0+ digits, letters, spaces, @, & or $ chars
  • $ - end of string.
like image 78
Wiktor Stribiżew Avatar answered Oct 21 '25 11:10

Wiktor Stribiżew


you can do it with the following regex

^(?!\d+$)\w+\S+

check the demo here

like image 30
marvel308 Avatar answered Oct 21 '25 11:10

marvel308



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!