Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning only part of match from Regular Expression

Tags:

c#

regex

Say I have the string "User Name:firstname.surname" contained in a larger string how can I use a regular expression to just get the firstname.surname part?

Every method i have tried returns the string "User Name:firstname.surname" then I have to do a string replace on "User Name:" to an empty string.

Could back references be of use here?

Edit:

The longer string could contain "Account Name: firstname.surname" hence why I want to match the "User Name:" part of the string aswell to just get that value.


1 Answers

I like to use named groups:

Match m = Regex.Match("User Name:first.sur", @"User Name:(?<name>\w+\.\w+)");
if(m.Success)
{
   string name = m.Groups["name"].Value;
}

Putting the ?<something> at the beginning of a group in parentheses (e.g. (?<something>...)) allows you to get the value from the match using something as a key (e.g. from m.Groups["something"].Value)

If you didn't want to go to the trouble of naming your groups, you could say

Match m = Regex.Match("User Name:first.sur", @"User Name:(\w+\.\w+)");
if(m.Success)
{
   string name = m.Groups[1].Value;
}

and just get the first thing that matches. (Note that the first parenthesized group is at index 1; the whole expression that matches is at index 0)

like image 192
Daniel LeCheminant Avatar answered Sep 13 '25 06:09

Daniel LeCheminant