ComeçarComece de graça

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 '').

Este exercício faz parte do curso

Practicing Coding Interview Questions in Python

Ver curso

Exercício interativo prático

Experimente este exercício completando este código de exemplo.

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

# Print the temperatures out
print(re.findall(pattern, text))
Editar e executar o código