Reputation: 87
I have a C# Regex like
[\"\'\\/]+
that I want to use to evaluate and return error if certain special characters are found in a string.
My test string is:
\test
I have a call to this method to validate the string:
public static bool validateComments(string input, out string errorString)
{
errorString = null;
bool result;
result = !Regex.IsMatch(input, "[\"\'\\/]+"); // result is true if no match
// return an error if match
if (result == false)
errorString = "Comments cannot contain quotes (double or single) or slashes.";
return result;
}
However, I am unable to match the backslash. I have tried several tools such as regexpal and a VS2012 extension that both seem to match this regex just fine, but the C# code itself won't. I do realize that C# is escaping the string as it is coming in from a Javascript Ajax call, so is there another way to match this string?
It does match /test or 'test or "test, just not \test
Upvotes: 3
Views: 15952
Reputation: 19423
You can solve this by making the string verbatim like this @
:
result = !Regex.IsMatch(input, @"[\""\'\\/]+");
Upvotes: 3
Reputation: 726539
Since backslashes are used as escapes inside regex themselves, I find it best to use verbatim strings when working with the regex library:
string input = @"\test";
bool result = !Regex.IsMatch(input, @"[""'\\]+");
// ^^
// You need to double the double-quotes when working with verbatim strings;
// All other characters, including backslashes, remain unchanged.
if (!result) {
Console.WriteLine("Comments cannot contain quotes (double or single) or slashes.");
}
The only issue with that is that you must double your double-quotes (which is ironically what you need to do in your case).
Upvotes: 2
Reputation: 111850
The \
is used even by Regex(es). Try "[\"\'\\\\/]+"
(so double escape the \
)
Note that you could have @"[""'\\/]+
" and perhaps it would be more readable :-) (by using the @
the only character you have to escape is the "
, by the use of a second ""
)
You don't really need the +
, because in the end [...]
means "one of", and it's enough for you.
Don't eat what you can't chew... Instead of regexes use
// result is true if no match
result = input.IndexOfAny(new[] { '"', '\'', '\\', '/' }) == -1;
I don't think anyone ever lost the work because he preferred IndexOf
instead of a regex :-)
Upvotes: 8
Reputation: 10184
For the trivial case, I am able to use regexhero.net for your test expression using the simple:
\\
to validate
\test
The code generated by RegExHero:
string strRegex = @"\\";
RegexOptions myRegexOptions = RegexOptions.IgnoreCase;
Regex myRegex = new Regex(strRegex, myRegexOptions);
string strTargetString = @"\test";
foreach (Match myMatch in myRegex.Matches(strTargetString))
{
if (myMatch.Success)
{
// Add your code here
}
}
Upvotes: 0