Cory
Cory

Reputation: 2312

Regex to extract sport score

I have string values with the follow pattern

"Buffalo Bill's 14, NewYork Giants 24 Final"

My goal is to capture each team name and the corresponding score and game status with regex

  1. Buffalo Bill's
  2. 14
  3. NewYork Giants
  4. 24
  5. Final

I tried the following, but this only got me the team and score combined.

(?<Score>[\w\s']+\s\d+)

Upvotes: 1

Views: 113

Answers (1)

The fourth bird
The fourth bird

Reputation: 163632

The pattern that you tried matches the team and the score combined because the character class [\w\s']+ also matches a whitespace \s and \w can also match a digit.

If there are always 5 parts and the digits and the comma are always present, for the first and the third part you could start the match with a word character (Or \S to match a non whitespace char) and then match as least chars as possible till the next encounter of a space and 1+ digits.

For the second and fourth part, you can capture 1+ digits and for the fifth part start the match again with a word character followed by the rest of the line or just \w+ to only match Final.

^(\w.*?) (\d+), (\w.*?) (\d+) (\w.*)

Regex demo

Upvotes: 1

Related Questions