0

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?

ndnenkov
  • 35,425
  • 9
  • 72
  • 104
StepUp
  • 36,391
  • 15
  • 88
  • 148

1 Answers1

3

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]+$"
ndnenkov
  • 35,425
  • 9
  • 72
  • 104
  • 2
    Awesome! Thank you very much! :) – StepUp Sep 02 '16 at 18:20
  • 1
    Just FYI: there is no point escaping a `/` symbol since it is no special regex metacharacter and [no regex delimiters are necessary (and allowed) when defining C# regex](http://stackoverflow.com/questions/31560080/removing-all-non-word-characters-with-regex-regex-delimiters-in-c-sharp-regular) (in Perl-like regexps, `/` is a usual regex delimiter). All the modifiers are passed as flags to the regex methods, or inline versions are used, and as for actions, there are just specific methods in the Regex class. – Wiktor Stribiżew Sep 02 '16 at 18:37