Shane Castle
Shane Castle

Reputation: 1759

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

Thanks.

Upvotes: 1

Views: 441

Answers (5)

csharptest.net
csharptest.net

Reputation: 64218

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.

Upvotes: 0

Thomas Levesque
Thomas Levesque

Reputation: 292425

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

Upvotes: 0

Mark Byers
Mark Byers

Reputation: 838216

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

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

Upvotes: 1

Amber
Amber

Reputation: 526613

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

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1062780

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)

Upvotes: 10

Related Questions