Prasad Prasad - 3 years ago 121
C# Question

Regex to identify if a string contains backslash comma or caret

Pretty straightforward.. I'm new to regex and was wondering how I can perform something like this? Initially I went with:

if (Regex.IsMatch(par, "^[0-9a-zA-Z]+$"))


But it doesn't seem to be working.. I'm looking for something that specifically excludes backslash, comma and the caret.

I'm also looking for another expression to specifically check if dollar sign ($), comma (,), or period (.) exist in a string

Answer Source

You seem to be looking for

@"^[^,\\^]*$"

See the regex demo

Details:

  • ^ - start of string
  • [^,\\^]* - zero or more chars other than ,, \ and ^
  • $ - end of string.

Note that [^...] defines a negated character class that matches any chars but the ones specified in the class. Note that the second ^ inside the brackets is considered a literal caret (while the first one is a part of the negated character class construct).

If you do not allow an empty string, replace * (zero or more occurrences) with + (one or more occurrences).

To further create regexps like this, just put the chars into the negated character class remembering that ], \, ^ and - are better escaped to avoid confusion. The $, *, (, ), +, |, {, ?, . lose their special meaning, and denote the literal symbols.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download