Reputation: 785
I would like my reg ex to accept characters in the set [a-zA-Z0-9.\?!%, ] and also not except the exact words "not set".
Examples of successful matches:
category1
myCategory
Hello World!!!
notset
Examples of unsuccessful matches:
{empty string}
not set
Not Set
NOT SET
<script>
I am using the .NET framework.
Thanks!
Upvotes: 2
Views: 3916
Reputation: 785
I ended up using
^(?![nN][oO][tT] [sS][eE][tT]$)[a-zA-Z0-9.?!%, ]+$
When using (?i:) in my .net validators and unobtrusive javascript I noticed my client side validation was getting disabled.
Upvotes: 0
Reputation:
This might work ^(?i:(?!not set)[a-z0-9.\\?!%, ])+$
(untested)
EDIT
Didn't work for me. – Bob 4 hours ago
@Bob - Here are your samples.
Examples of successful matches:
category1
myCategory
Hello World!!!
notset
Examples of unsuccessful matches:
{empty string}
not set
Not Set
NOT SET
<script>
What didn't work?
@samples = (
'category1',
'myCategory',
'Hello World!!!',
'notset',
'',
'not set',
'Not Set',
'NOT SET',
'<script>'
);
for (@samples) {
print "'$_'";
if (/^(?i:(?!not set)[a-z0-9.\\?!%, ])+$/) {
print " - yes matches\n";
}
else {
print " - no\n";
}
}
output:
'category1
' - yes matches
'myCategory
' - yes matches
'Hello World!!!
' - yes matches
'notset
' - yes matches
'' - no
'not set
' - no
'Not Set
' - no
'NOT SET
' - no
'<script>
' - no
Upvotes: 2
Reputation: 138027
Obviosly, you can test for "not set" by code. If it has to be a regex, you can use a negative lookahead:
^(?!not set$)[a-zA-Z0-9.?!%, ]+$
A C# code example would be:
Match m = Regex.Match(s, @"^(?!not set$)[a-zA-Z0-9.?!%, ]+$", RegexOptions.IgnoreCase);
if (m.Success)
{
// all is well
}
If you want the match to be case insensitive (that is "Not Set" is invalid, but "not set" is valid), use:
Match m = Regex.Match(s, @"^(?!Not Set$)[a-zA-Z0-9.?!%, ]+$");
Upvotes: 9
Reputation: 1884
You can try the following code:
static void Main(string[] args)
{
string str = "NOT SET";
if (str.ToLower().Equals("not set"))
{
// Do Something
}
else
{
String pattern = @"^[a-z0-9.\?!%,]+$";
Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);
if (regex.IsMatch(str))
{
// Do Something
}
}
}
Upvotes: 1