Regular expression help.

Associate
Joined
1 Jun 2007
Posts
840
Im trying to write a regular expression which captures the away side in a team:
Exact sample:

"Hull City 0 - 0 Liverpool "
"Man Utd 4 - 0 Stoke City "
"West Ham 1 - 1 Man City "
"Wolves 2 - 1 Sunderland"

I want to match Liverpool, Stoke City, Man City, Sunderland.
There is whitespace before and after the words but no whitespace after Sunderland.

PS: I put quotes in just for OC website to show the whitespace, they are not in the
orginal sample.

Any help?
 
I wrote a php script to test the regex, but you can just take the regex if you want to use it in some other language.


PHP:
<?php




$subject = '
"Hull City 0 - 0 Liverpool "
"Man Utd 4 - 0 Stoke City "
"West Ham 1 - 1 Man City "
"Wolves 2 - 1 Sunderland"';
//input

$pattern = '/([a-z ]+) ([0-9]+) - ([0-9]+) ([a-z ]+)/i';
//regex pattern

preg_match_all($pattern, $subject, $matches);
//apply the regex pattern to the string and return all matches in the matches array

$awaySidesArray = $matches[4];
//index 1 matches the first regex variable, the 4th variable contains the away side

//this is almost perfect, but we just need to trim the whitespace off the end of the team names

$awaySides = array_map('trim',$awaySidesArray);
//trim (remove whitespace) from all elements of the array

print_r($awaySides);
//output the final array

?>
 
Back
Top Bottom