|
| 1 | +#16 - EXPRESIONES REGULARES |
| 2 | +""" |
| 3 | + * EJERCICIO: |
| 4 | + * Utilizando tu lenguaje, explora el concepto de expresiones regulares, |
| 5 | + * creando una que sea capaz de encontrar y extraer todos los números |
| 6 | + * de un texto. |
| 7 | + * |
| 8 | + * DIFICULTAD EXTRA (opcional): |
| 9 | + * Crea 3 expresiones regulares (a tu criterio) capaces de: |
| 10 | + * - Validar un email. |
| 11 | + * - Validar un número de teléfono. |
| 12 | + * - Validar una url. |
| 13 | +""" |
| 14 | + |
| 15 | +import re |
| 16 | + |
| 17 | +def extract_numbers(text:str)-> str: |
| 18 | + |
| 19 | + numbers = re.findall('[\d]+',text) |
| 20 | + |
| 21 | + #To find commas, e.g. 12,300 or 12,300.00 |
| 22 | + #r'[\d]+[.,\d]+' |
| 23 | + #To find floats, e.g. 0.123 or .123 |
| 24 | + #r'[\d]*[.][\d]+' |
| 25 | + #To find integers, e.g. 123 |
| 26 | + #r'[\d]+' |
| 27 | + |
| 28 | + all_numbers = "".join(numbers) |
| 29 | + return all_numbers |
| 30 | + |
| 31 | +print(extract_numbers("hello23 numbers 1234, not")) |
| 32 | + |
| 33 | +print(extract_numbers("hello 2,3 numbers 1234, not")) |
| 34 | + |
| 35 | + |
| 36 | +#EXTRA: |
| 37 | +#Validate EMAIL: |
| 38 | +def validEmail(email): |
| 39 | + regexEmail = re.compile(r'([A-Za-z0-9]+[.-_])*[A-Za-z0-9]+@[A-Za-z0-9-]+(\.[A-Z|a-z]{2,})+') |
| 40 | + if re.fullmatch(regexEmail, email): |
| 41 | + print("Valid email") |
| 42 | + else: |
| 43 | + print("Invalid email") |
| 44 | + |
| 45 | + |
| 46 | + |
| 47 | +validEmail("saezmd@gmail") |
| 48 | + |
| 49 | + |
| 50 | + |
| 51 | +#Validate Phone Number: |
| 52 | +def validPhone(phoneNumber): |
| 53 | + regexPhone = re.compile(r'^(\+\d{1,2}|00\d{2})?[ -]*(6|7)[ -]*([0-9][ -]*){8}$') |
| 54 | + phoneNumber = str(phoneNumber) |
| 55 | + if re.fullmatch(regexPhone, phoneNumber): |
| 56 | + print("Valid phone") |
| 57 | + else: |
| 58 | + print("Invalid phone") |
| 59 | + |
| 60 | +validPhone("0034612358902") |
| 61 | +validPhone("+34612358902") |
| 62 | +validPhone(612358902) |
| 63 | +validPhone("+34239847298435") |
| 64 | + |
| 65 | +#Validate URL: |
| 66 | + |
| 67 | +def validURL(URLlink): |
| 68 | + regexURL = re.compile( |
| 69 | + r'^(?:http|ftp)s?://' # http:// or https:// |
| 70 | + r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' #domain... |
| 71 | + r'localhost|' #localhost... |
| 72 | + r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip |
| 73 | + r'(?::\d+)?' # optional port |
| 74 | + r'(?:/?|[/?]\S+)$', re.IGNORECASE) |
| 75 | + |
| 76 | + if re.fullmatch(regexURL, URLlink): |
| 77 | + print("Valid URL") |
| 78 | + else: |
| 79 | + print("Invalid URL") |
| 80 | + |
| 81 | + |
| 82 | +validURL("http://www.saezMD.com") |
| 83 | +validURL("example.com") |
| 84 | +validURL("https://saezmd.vercel.app/") |
| 85 | + |
| 86 | + |
| 87 | + |
| 88 | + |
0 commit comments