Ofir Hadad
Ofir Hadad

Reputation: 1900

Regex.Matches return zero result

I'm pretty sure I'm doing something wrong here, but I can't point on the problem.

I have this line in my C# code:

string match = "Test - Wow";
MatchCollection contact = Regex.Matches(match, "-");

//Expected output in contact : contact[0]=="Test " & contact[1]==" Wow" ; 

But for some reason contact return empty, Meaning no match for "-". I even tried @"-", "(-)", "(-)*", "[-]", "([-]*)" but nothing works. What am I doing wrong?

Upvotes: 0

Views: 846

Answers (3)

xanatos
xanatos

Reputation: 111890

No, it doesn't. It works correctly!

string match = "Test - Wow";
MatchCollection contact = Regex.Matches(match, "-");
int count = contact.Count; // returns 1
Match onematch = contact[0];
string str = onematch.ToString(); // returns -

Test here http://ideone.com/LWTQWn

If you want a regex that will return ALL the string if a - is present, something like this .*-.* will do (any number of any character, one -, any number of any character)

Upvotes: 1

Anton
Anton

Reputation: 9961

You do not need regex for this task. Better to use split function.

 "Test - Wow".Split('-').Select(x => x.Trim())

Upvotes: 1

Dev.Jaap
Dev.Jaap

Reputation: 151

  • is a reserverd character for a Regex. You 'll need "-" (slash-minus). What will be found is '-'. When you want to find Test and Wow you have to use the Regex.Split() function.

Upvotes: 1

Related Questions