tags:

views:

325

answers:

4

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.

+9  A: 

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)

Daniel LeCheminant
That is great, thanks a lot.
+1  A: 

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.

David Sykes
A: 

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)

Tor Haugen
A: 

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