Reputation: 2108
I am trying to match the below string. I am not able to get it right. Could someone please help?
string str = "test\tester";
if (Regex.IsMatch(str, "/\\/"))
MessageBox.Show("Match");
else
MessageBox.Show("Not match");
I am wondering what is the Regex pattern I should use to get this matched.
Upvotes: 0
Views: 1284
Reputation: 7961
Simply use: Regex.IsMatch(str, @".*\\.*")
The double \
is used to escape the backslash.
Upvotes: 1
Reputation: 25053
I suspect your test code is wrong.
What you're testing:
string str = "test\tester";
But if what you're getting is "two parameters separated by a backslash", this should be
string str = "test\\tester";
This is because a backslash is represented in a constant as \\
. Because \t
happens to represent a tab character, your test code isn't throwing an error at compile time. If you did this:
string str = "mytest\mytester";
You'll get an error, because \m
isn't valid.
Upvotes: 1
Reputation: 19636
In this case, you're way better of using string.Contains()
from a performance point of view:
string str = @"test\tester"; //<- note the @
if (str.Contains("\\"))
MessageBox.Show("Match");
else
MessageBox.Show("Not match");
Be aware that in your test original string, you need to escape the \
or @
the string.
Upvotes: 2
Reputation: 1243
The regex for a single backslash is \\
. If you want to make the string match exactly in C#, use the @
operator:
Regex.IsMatch(str, @".*\\.*")
Alternatively, you can use C#'s escape characters:
Regex.IsMatch(str, ".*\\\\.*")
Upvotes: 0