Skip to main content
 首页 » 编程设计

c#之微软下的正则表达式

2024年01月26日26mq0036

我想知道一个很简单的事情:一个字符串以反斜杠结尾是yes还是no?

string bla = @"C:\"; 
if ( ! Regex.IsMatch(bla, "\b$")) { bla = bla + @"\"; } 

但它不起作用。如果字符串末尾没有斜杠,我想添加一个斜杠。我尝试了几种方法,即使我只是尝试匹配反斜杠,而不必将其放在字符串的末尾,这是一个大问题:

Regex.IsMatch(bla, "\b") // Not working 
Regex.IsMatch(bla, @"\") // Giving me and exception even! 
Regex.IsMatch(bla, @"\\$") // not working 

我别无选择。我如何将反斜杠与 C# 匹配?

请您参考如下方法:

I want to know a very simple thing: does a string end with a backslash yes or no.

那么你不需要正则表达式...

string str = "your string here"; 
str.EndsWith(@"\"); // true or false 

如果你真的想用正则表达式的方式来做,你只需要确保你的正则表达式是正确的。这应该有效:

.*\\$ 
 
.* will match any optional leading characters 
\\ will match the '\' and has been escaped with another '\' 
$ will match until the end of your string.