Apqu
Apqu

Reputation: 5031

Regex to match all alphanumeric and certain special characters?

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.

Upvotes: 3

Views: 20261

Answers (3)

Jerry
Jerry

Reputation: 71588

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

Upvotes: 5

Kaveh Shahbazian
Kaveh Shahbazian

Reputation: 13523

This code does that:

var input = "Test if / this+-works&sec0nd 2 part*3rd    part";
var matches = Regex.Matches(input, @"([0-9a-zA-Z /+-]+)");

foreach (Match m in matches) if (m.Success) Console.WriteLine(m.Value);

And output will have 3 result lines:

  • Test if / this+-works
  • sec0nd 2 part
  • 3rd---part (I showed spaces with - here)

Upvotes: 0

PhonicUK
PhonicUK

Reputation: 13864

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.

Upvotes: 3

Related Questions