views:

37

answers:

3

I want to enable my users to specify the allowed characters in a given string.

So... Regex's are great but too tough for my users.

my plan is to enable users to specify a list of allowed characters - for example

a-z|A-Z|0-9|,

i can transform this into a regex which does the matching as such:

[a-zA-Z0-9,]*

However i'm a little lost to deal with all the escaping - imagine if a user specified

a-z|A-Z|0-9| |,|||\|*|[|]|{|}|(|)

Clearly one option is to deal with every case individually but before i write such a nasty solution - is there some nifty way to do this?

Thanks

David

A: 

To make it as simple as possible for your users, why don't you ditch the "|" and the concept of character ranges, e.g., "a-z", and get them just to type the complete list of characters they want to allow:

abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890 *{}()

You get the idea. I think this will be much simpler.

ShellShock
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890 is mighty nasty to write - A-Za-z0-9 are far more concise
GreyCloud
So these are users who are happy with a-z but not with the full regex syntax?
ShellShock
+2  A: 

Forget regex, here is a much simpler solution:

bool isInputValid = inputString.All(c => allowedChars.Contains(c));
BlueCode
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890 is mighty nasty to write - A-Za-z0-9 are far more concise
GreyCloud
Write a method to expand the collapsed forms of those character ranges.
BlueCode
+1  A: 

You might be right about your customers, but you could provide some introductory regex material and see how they get on - you might be surprised.

If you really need to simplify, you'll probably need to jetison the use of pipe characters too, and provide an alternative such as putting each item on a new line (in a multi line text box for instance).

Ed Guiness
I agree. It be much easier to allow the regex engine to validate the provide pattern than code up all the error handling to deal with all the situations presented by the user. Those that would have problems with basic patterns for a simple match like this would also have issues with the piped ranges presented here. Unless you provide some kind of character map to allow them to select what they want or ranges, you'll have to handle mixed casing in the ranges, etc.
Benjamin Anderson