tags:

views:

60

answers:

3

I've got a regular expression like this

something (.*) someotherthing

How do I use a Regex object to match the entire expression and get the value of the capture?

+1  A: 

Regex.Match

http://msdn.microsoft.com/en-us/library/twcw2f1c.aspx

Patrick
+1  A: 

Where you can use $1 to get that group, you can use $0 to get the entire expression.

This works in most regex variants (may be \0 or %0 or whatever), not just C#.

Similarly, the Match.Groups property should work with 0 as an argument to return the whole match, otherwise Capture.Value looks like it contains the match.


Also worth noting, to ensure your test string matches the entire expression, it's generally a good idea to prefix with ^ and suffix with $ which are zero-width position anchors for start and end of string. (Also start/end of line in multiline mode.)

Peter Boughton
+3  A: 

Here is an example of what I think you are asking for:

Match m = Regex.Match( "something some stuff in the middle someotherthing", 
         "something (.*) someotherthing" );
if ( m.Success )
   Console.WriteLine( "groups={0}, entire match={1}, first group={2}", 
                      m.Groups.Count, m.Groups[0].Value, 
                      m.Groups[1].Value );
Mark Wilkins