I’m working in .NET (C# 4.0); How do I write an expression that matches on an text that contains a ‘?’ or a space ‘\S’?
GlennTest (should not match)
Glenn?Test (should match)
Glenn Test (should match)
Glenn? Test (should match)
Glenn ?Test (should match)
?Glenn Test (should match)
I am able to write expressions to find one, but combining them is giving me trouble.
CLARIFICATION:
I am clarifying my question because neither of the responses thus far worked.
I am writing an MVC app with the following RegExp Attribute on one of the properties, which appears to work as designed (doesnt allow spaces).
[DataMember(Name="Job Code")]
[Required(ErrorMessage="Job Code is required.")]
[RegularExpression(@"^\S*$", ErrorMessage = "Spaces are not allowed in the Job Code")]
public string JobCode { get; set; }
That said, I want to extend this capability to disallow ‘?’ question marks as well.
I also want the ability to test this in code, not on a MVC View using code like this:
public static bool IsValidCode(string code, out string message)
{
message = "";
const string NO_QMS_REG_EXP = @"^\?*$";
const string NO_SPACES_REG_EXP = @"^\S*$";
var expr1 = new Regex(NO_QMS_REG_EXP);
var expr2 = new Regex(NO_SPACES_REG_EXP);
if (expr1.IsMatch(code))
{
message = "Code cannot contain a question mark";
return false;
}
if (expr2.IsMatch(code))
{
message = "Code cannot contain a space";
return false;
}
// TODO: One expression that validates both simulatenously??
return true;
}
MVC3 question: Can I programmatically execute the properties Regex Attrib validation?
You could also try
This matches any string that contains neither spaces nor question marks.