Get startedGet started for free

Write a regular expression

Let's write some regular expressions!

Your task is to create a regular expression matching a valid temperature represented either in Celsius or Fahrenheit scale (e.g. '+23.5 C', '-4 F', '0.0 C', '73.45 F') and to extract all the appearances from the given string text. Positive temperatures can be with or without the + prefix (e.g. '5 F', '+5 F'). Negative temperatures must be prefixed with -. Zero temperature can be used with a prefix or without.

The re module is already imported.

Tips:

  • The + symbol within the square brackets [] matches the + symbol itself (e.g. the regular expression [1a+] matches to '1', 'a', or '+').
  • You can also apply ? to the characters within the square brackets [] to make the set optional (e.g. [ab]? matches to 'a', 'b', or '').

This exercise is part of the course

Practicing Coding Interview Questions in Python

View Course

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Define a pattern to search for valid temperatures in text
pattern = re.compile(____)

# Print the temperatures out
print(re.findall(pattern, text))
Edit and Run Code