Returning only part of match from Regular Expression

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)


You could also try the concept of "lookaround". This is a kind of zero-width assertion, meaning it will match characters but it won't capture them in the result.

In your case, we could take a positive lookbehind: we want what's behind the target string "firstname.surname" to be equal to "User Name:".

Positive lookbehind operator: (?<=StringBehind)StringWeWant

This can be achieved like this, for instance (a little Java example, using string replace):

String test = "Account Name: firstname.surname; User Name:firstname.surname";
String regex = "(?<=User Name:)firstname.surname";
String replacement = "James.Bond";
System.out.println(test.replaceAll(regex, replacement));

This replaces only the "firstname.surname" strings that are preceeded by "User Name:" without replacing the "User Name:" itself - which is not returned by the regex, only matched.

OUTPUT: Account Name: firstname.surname; User Name:James.Bond

That is, if the language you're using supports this kind of operations


Make a group with parantheses, then get it from the Match.Groups collection, like this:

string s = "User Name:firstname.surname";
Regex re = new Regex(@"User Name:(.*\..*)");
Match match = re.Match(s);
if (match.Success)
{
    MessageBox.Show(match.Groups[1].Value);
}

(note: the first group, with index 0, is the whole match)


All regular expression libraries I have used allow you to define groups in the regular expression using parentheses, and then access that group from the result.

So, your regexp might look like: User name:([^.].[^.])

The complete match is group 0. The part that matches inside the parentheses is group 1.