简体   繁体   English

偷偷摸摸的反斜杠的情况-Regex

[英]The case of the sneaky backslash - Regex

I'm missing something very obvious here, but I just cant see it. 我在这里缺少很明显的东西,但是我看不到。

I've got: 我有:

string input = @"999\abc.txt";
string pattern = @"\\(.*)";
string output = Regex.Match(input,pattern).ToString();
Console.WriteLine(output);

My result is: 我的结果是:

\abc.txt

I don't want the slash and cant figure out why it's sneaking into the output. 我不要斜线 ,也无法弄清楚为什么它会潜入输出中。 I tried flipping the pattern, and the slash winds up in the output again: 我尝试翻转模式,斜线再次出现在输出中:

string pattern = @"^(.*)\\";

and get: 并得到:

999\

Strange. 奇怪。 The result is fine in Osherove's Regulator. 在Osherove的调节器中,结果很好。 Any thoughts? 有什么想法吗?

Thanks. 谢谢。

The Match is the entire match; Match整个比赛; you want the first group; 你想要第一组;

string output = Regex.Match(input,pattern).Groups[1].Value;

(from memory; may vary slightly) (根据内存;可能略有不同)

使用网上论坛仅获取网上论坛 ,而不是整个比赛:

string output = Regex.Match(input, pattern).Groups[1].Value;

You need to look at the results in Groups , not the entire matched text. 您需要查看“ Groups中的结果,而不是整个匹配的文本。

http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.match.groups(v=VS.71).aspx http://msdn.microsoft.com/zh-CN/library/system.text.regularexpressions.match.groups(v=VS.71).aspx

As an alternative to Marc's answer, you can use a zero-width positive lookbehind assertion in your pattern : 作为Marc答案的替代方法,您可以在模式中使用零宽度正向后断言

string pattern = @"(?<=\\)(.*)";

This will match "\\" but exclude it from the capture 这将匹配“ \\”,但将其从捕获中排除

You could try the match prefix/postfix but exclude options. 您可以尝试匹配前缀/后缀,但可以排除选项。

Match everything after the first slash / 在第一个斜杠后匹配所有内容/

(?<=\\)(.*)$

Match everything after the last slash / 匹配最后一个斜杠之后的所有内容/

(?<=\\)([^\\]*)$

Match everything before the last slash / 匹配最后一个斜杠之前的所有内容/

^(.*)(?=\\)

BTW, download Expresso for testing regular expressions, total life-saver. 顺便说一句,下载Expresso以测试正则表达式,可以节省总时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM