Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to match all alphanumeric and certain special characters?

Tags:

c#

regex

I am trying to get a regex to work that will allow all alphanumeric characters (both caps and non caps as well as numbers) but also allow spaces, forward slash (/), dash (-) and plus (+)?

I've got a start but so far no success.

like image 860
Apqu Avatar asked Jan 28 '26 02:01

Apqu


2 Answers

If you want to allow only those, you will also need the use of the anchors ^ and $.

^[a-zA-Z0-9_\s\+\-\/]+$
^                    ^^

This is your regex and I added characters as indicated from the second line. Don't forget the + or * near the end to allow for more than 1 character (0 or more in the case of *), otherwise the regex will try to match only one character, even with .Matches.

You can also replace the whole class [A-Za-z0-9_] by one \w, like so:

^[\w\s\+\-\/]+$

EDIT:

You can actually avoid some escaping and avoid one last escaping with a careful placement (i.e. ensure the - is either at the beginning or at the end):

^[\w\s+/-]+$
like image 112
Jerry Avatar answered Jan 30 '26 15:01

Jerry


Your regex would look something like:

/[\w\d\/\-\+ ]+/g

That's all letters, digits, and / - + and spaces (but not any other whitespace characters)

The + at the end means that at least 1 character is required. Change it to a * if you want to allow an empty string.

like image 40
PhonicUK Avatar answered Jan 30 '26 14:01

PhonicUK



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!