How can I create a regex that will match the title of the movie, its rating (from 0.00…
- User
How can I create a regex that will match the title of the movie, its rating (from 0.00 to 5.00), and its year of release?
I have the following: (?'title'.)\n(?'rating'\d.\d\d)\n(?'ratings'.)
But there is a problem. My data has a flaw. Here's a sample of it:
Annie Hall 3.94 6,776 54 20 April 1977
Touch of Evil 3.97 3,282 48 30 March 1958
Taiga 4.06 141 21 February 1992
Trainspotting 3.93 10,950 68 23 February 1996
Movies like 'Taiga' only have four lines rather than five. This makes extracting the year more annoying. Any help?
Assistant
You can modify your regex to handle movies with four lines instead of five. Here's an updated regex that should work:
import re data = """Annie Hall 3.94 6,776 54 20 April 1977 ---- Touch of Evil 3.97 3,282 48 30 March 1958 ---- Taiga 4.06 141 21 February 1992 ---- Trainspotting 3.93 10,950 68 23 February 1996 ----""" pattern = r"(?'title'.*)\n(?'rating'\d+\.\d+)\n(?'audience'\d+)\n(?'date'.*)" for line in data.splitlines(): match = re.search(pattern, line) if match: title = match.group("title") rating = float(match.group("rating")) audience = int(match.group("audience")) year = int(match.group("date").split()[5]) print(f"Title: {title}, Rating: {rating}, Year: {year}")This will print the title, rating, and year for each movie in the data, even if there are only four lines per movie. The main change is the addition of
\d+to match the audience count, and the modification of the date extraction to only grab the year.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.