tags:

views:

89

answers:

3

The regex foo/(\w*)/bar matches the string foo/123/bar.

This is probably something basic that I've missed about regexes, but often I only want to retrieve the substring between the slashes. Is there a simple .NET API I can use without having to access the groups collection? Or an alternative way of writing the regex?

Thanks!

+1  A: 

The short answer is no, but it really is no hassle to get the capture:

string cap = Regex.Match(inputString, @"foo/(\w*)/bar").Groups[1].ToString();
Aviad P.
I would prefer a longer answer! Can you actually back that up? Please answer the question; don't just show me how to access the Groups collection in C#.
Pete Montgomery
I'm sorry if I offended you, perhaps one of the other answers suits you better.
Aviad P.
Sorry to be short. I'm asking a specific question. If you have any supporting information about *why* the answer is no, then I would be very grateful!
Pete Montgomery
+1  A: 

It is possible using lookaround:

(?<=foo/)\w*(?=/bar) 

applied to foo/123/bar. matches "123". Groups are a better method and bear in mind that lookaround (in particular look behind) is not supported in all regex tools, but it is in .net.

note: \w is shorthand for a character class, you don't need to put it inside []

Paul Creasey
Thanks for the note. I'll edit the question!
Pete Montgomery
System.ArgumentException: parsing "(?<foo/)\w*(?=/bar)" - Invalid group name: Group names must begin with a word character.
Pete Montgomery
typo in the lookbehind, fixed
Paul Creasey
When using lookaround you might get overlapping results, for example on: `foo/foo/bar/bar`
Aviad P.
Indeed, in fact, overlapping results are largely the purpose of lookaround!
Paul Creasey
A: 

If the string is guaranteed to be matched, and you only want the substring between the two slashes, String.Split can be used instead of Regular Expression:

String sub = str.Split('/')[1]
Iamamac
+1 for simpllicity
Paul Creasey
Thanks, but the question is about the regex language - this is just an example.
Pete Montgomery
The point is that I want to *match* the string matched by the regex but *retrieve* the substring in the group.
Pete Montgomery