tags:

views:

71

answers:

5

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. Any thoughts?

Thanks.

+10  A: 

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)

Marc Gravell
Ah! Beat me to it.
Callum Rogers
Yup, that did it. Thanks.
Shane Cusson
Just to clarify for anyone wondering why it's index of 1 instead of index of 0 into groups, it's because index of 0 gives back a group which represents the entire match.
John JJ Curtis
A: 

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

Amber
+1  A: 

Use Groups to get only the group, not the entire match:

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

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

Thomas Levesque
A: 

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.

csharptest.net