StepUp StepUp - 3 months ago 18
C# Question

Regular expression for signs which depends alphanumeric

The row should be:


  • contains alphanumeric, dot sign
    .
    and minus sign
    -
    , spaces, underscore, slash

  • if there is no alphanumeric, then regular expression should return false



I've written the following
Regex
pattern:

string pattern = @"^[a-zA-Z0-9._\+\-\/\s]+$";


and the second condition is not satisfied:

string s1 = "."; // or dot, space, underscore, slash

// Compare a string against the regular expression
var isOK = new Regex(pattern).IsMatch(s1); // true, but I would like to be false


Could you tell me the right way to create a
Regex
pattern?

ndn ndn
Answer

Firstly, there is a character set, which contains [a-zA-Z0-9_] - \w. Secondly, you don't need to escape the + inside character sets.

As for the actual solution, you can just use a positive lookahead to guarantee at least one such character exists somewhere in the string after some number of characters (.*):

@"^(?=.*[a-zA-Z\d])[\w.+\-\/\s]+$"