[英]Regex pattern for single backslash
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. 我想知道我应该使用什么正则表达式模式来实现此匹配。
In this case, you're way better of using string.Contains()
from a performance point of view: 在这种情况下,从性能角度来看,最好使用string.Contains()
:
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. 请注意,在测试原始字符串中,需要转义\\
或@
字符串。
Simply use: Regex.IsMatch(str, @".*\\\\.*")
只需使用: Regex.IsMatch(str, @".*\\\\.*")
The double \\
is used to escape the backslash. double \\
用于转义反斜杠。
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. 因为\\t
恰好代表制表符,所以您的测试代码在编译时不会引发错误。 If you did this: 如果您这样做:
string str = "mytest\mytester";
You'll get an error, because \\m
isn't valid. 您会收到错误消息,因为\\m
无效。
The regex for a single backslash is \\\\
. 单个反斜杠的正则表达式为\\\\
。 If you want to make the string match exactly in C#, use the @
operator: 如果要使字符串在C#中完全匹配,请使用@
运算符:
Regex.IsMatch(str, @".*\\\\.*")
Alternatively, you can use C#'s escape characters: 另外,您可以使用C#的转义字符:
Regex.IsMatch(str, ".*\\\\\\\\.*")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.