Regular expression captures

  • Thread starter Thread starter Erik Tamminga
  • Start date Start date
E

Erik Tamminga

Hi,

From the following string I would like to capture text.

String: This action has been executed via Console

First of all I like to know if this is the text I need: it must contain
"This action has been executed via".
Secondly I would like to know "Console"

How can Regular expressions help me in this. I've tried various things with
the RegEx class but I'm having troubles retrieving "Console". The
match.Captures collection always seems to contain the string searched, not
only the captured part.

RegEx r = RegEx( "This action has been executed", RegExOptions.IgnoreCase)
if (r.Matches( myString).Count > 0)
{
Here matches are found and r.Matches[0].Captures.Count > 0.
Why is ...Captures.Count > 0, I did ask for a capture?
}

RegEx q = RegEx( "(C\w+)", RegExOptions.IgnoreCase)
if (q.Matches( myString).Count > 0)
{
Here matches are found and r.Matches[0].Captures.Count > 0.
This is where I expected the capture!!
}


regards,

Erik
 
Erik said:
From the following string I would like to capture text.

String: This action has been executed via Console

First of all I like to know if this is the text I need: it must contain
"This action has been executed via".
Secondly I would like to know "Console"

How can Regular expressions help me in this. I've tried various things with
the RegEx class but I'm having troubles retrieving "Console". The
match.Captures collection always seems to contain the string searched, not
only the captured part.

The captures will always include the substring that matches the whole
regex in the Match object and in Groups[0]. Explicit captures start at
Groups[1]. This is by design, and broadly matches the behavior of Perl
regexes.

Try using

Regex("This action has been executed via (.*)",
RegExOptions.IgnoreCase)

and looking at Groups[1].
if (r.Matches( myString).Count > 0)

Don't write code like this. Readings Matches.Count forces the regex to
find every match. Use

Match M = R.Match(Text);
if (M.Success)
string Capture = M.Groups[1].Value;
 

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

Back
Top