regular expressions pression the middle name expression matches zero or more occurrences of whitespace followed by word the second part of the regex\ +(\ +)matches the whitespace that follows the forename (and middle namesand the surname if the regex looks bit too much like line noisewe can use named capture groups to improve legibility and make it more maintainablename re sub( "(? \ +(?:\ +\ +)*) "\ +(? \ +)" "\ \ "namecaptured text can be referred to in sub(or subn(function or method by using the syntax \ or \ where is the number of the capture group and id is the name or number of the capture group--so \ is the same as \gand in this examplethe same as \ this syntax can also be used in the string passed to match object' expand(method why doesn' the first part of the regex grab the entire nameafter allit is using greedy matching in fact it willbut then the match will fail because although the middle names part can match zero or more timesthe surname part must match exactly oncebut the greedy middle names part has grabbed everything having failedthe regular expression engine will then backtrackgiving up the last "middle nameand thus allowing the surname to match although greedy matches match as much as possiblethey stop if matching more would make the match fail for exampleif the name is "john le carre"the regex will first match the entire namethat isjohn le carre this satisfies the first part of the regex but leaves nothing for the surname part to matchand since the surname is mandatory (it has an implicit quantifier of )the regex has failed since the middle names part is quantified by *it can match zero or more times (currently it is matching twiceleand carre")so the regular expression engine can make it give up some of its match without causing it to fail thereforethe regex backtracksgiving up the last \ +\ ( carre")so the match becomes john le carre with the match satisfying the whole regex and with the two match groups containing the correct texts there' one weakness in the regex as writtenit doesn' cope correctly with forenames that are written using an initialsuch as "james loewen"or " tolkeinthis is because \ matches word characters and these don' include period one obvious--but incorrect--solution is to change the forenames part of the regex' \wexpression to [\ ]+in both places that it occurs period in character class is taken to be literal periodand character class shorthands retain their meaning inside character classesso the new expression matches word characters or periods but this would allow for names like "" " "and so on in view of thisa more subtle approach is required