C# Regular Expressions not behaving?

C

christopher green

I’m new to regular expressions in c# and can’t get even basic searchs to
work as I believe they’re supposed to. The following example is where I
try to identify any word in a string:


this.filecontent = "the cat sat on the mat";

this.MethodSpotter = new Regex("(\\w+)",RegexOptions.IgnoreCase);

MatchCollection result = this.MethodSpotter.Matches
(this.filecontent);

The result is that I get an Unhandled exception saying item has already
been added.

The following example returns the entire string rather than just the
word “cat”, surely such behaviour is incorrect?

this.filecontent = "the cat sat on the mat";

this.MethodSpotter = new Regex("cat",RegexOptions.IgnoreCase);

MatchCollection result = this.MethodSpotter.Matches
(this.filecontent);

Also how do I ensure that a string must finish with a particular
character? The $ operator just seems to be ignored.

Many thanks for any assistance you may be able to offer.




*** Sent via Devdex http://www.devdex.com ***
Don't just participate in USENET...get rewarded for it!
 
U

Uri Dor

this works:
using System;
using System.Text.RegularExpressions;

namespace ConsoleApplication1
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
string s = "the cat sat on the mat";

Regex r = new Regex("(\\w+)",RegexOptions.IgnoreCase);

MatchCollection result = r.Matches(s);

Console.WriteLine(result.Count);
}
}
}


It's just a cut and paste from your code.
Please minimize your sample code next time - the problem is somewhere else.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top