Regex to match all alphanumeric and certain special characters?

19,655

Solution 1

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+/-]+$

Solution 2

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.

Share:
19,655
Apqu
Author by

Apqu

Software developer based in Suffolk, UK. Specialising in: ASP.NET (C#) Xamarin Development HTML / CSS JavaScript / JQuery SQL Server 2000 - 2019

Updated on June 07, 2022

Comments

  • Apqu
    Apqu almost 2 years

    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 have been playing with a refiddle: http://refiddle.com/gqr but so far no success, anyone any ideas?

    I'm not sure if it makes any difference but I am trying to do this in c#?

  • Apqu
    Apqu almost 11 years
    Thanks for the explanation, I managed to get it to work using your example, much appreciated! I was getting the multitude of single characters, your explanation not only resolved my issue but also helped me to learn why it wasn't working in the first place :-)