[ACCEPTED]-Returning only part of match from Regular Expression-regex

Accepted answer
Score: 41

I like to use named groups:

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

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

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

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

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

Score: 8

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

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

Positive lookbehind 8 operator: (?<=StringBehind)StringWeWant

This 7 can be achieved like this, for instance 6 (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 5 replaces only the "firstname.surname" strings 4 that are preceeded by "User Name:" without 3 replacing the "User Name:" itself - which 2 is not returned by the regex, only matched.

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

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

Score: 4

Make a group with parantheses, then get 3 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)

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

Score: 2

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

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

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

More Related questions