The case of the sneaky backslash - Regex
I'm missing something very obvious here, but I just cant s开发者_JAVA技巧ee 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. Any thoughts?
Thanks.
The Match
is the entire match; you want the first group;
string output = Regex.Match(input,pattern).Groups[1].Value;
(from memory; may vary slightly)
Use Groups to get only the group, not the entire match:
string output = Regex.Match(input, pattern).Groups[1].Value;
You need to look at the results in Groups
, not the entire matched text.
http://msdn.microsoft.com/en-us/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 :
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.
精彩评论