|
| 1 | +import Foundation |
| 2 | + |
| 3 | +func regExpr(_ cadena: String) { |
| 4 | + let pattern = #"-?\d*\.?\d+"# |
| 5 | + let regex = try! NSRegularExpression(pattern: pattern) |
| 6 | + let matches = regex.matches(in: cadena, range: NSRange(cadena.startIndex..., in: cadena)) |
| 7 | + |
| 8 | + print("Números encontrados:") |
| 9 | + for match in matches { |
| 10 | + if let range = Range(match.range, in: cadena) { |
| 11 | + print(String(cadena[range])) |
| 12 | + } |
| 13 | + } |
| 14 | + print("\n") |
| 15 | +} |
| 16 | + |
| 17 | +func emailValidation(_ email: String) { |
| 18 | + let pattern = #"^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$"# |
| 19 | + let regex = try! NSRegularExpression(pattern: pattern) |
| 20 | + if regex.firstMatch(in: email, options: [], range: NSRange(location: 0, length: email.utf16.count)) != nil { |
| 21 | + print("El email \(email) es válido.") |
| 22 | + } else { |
| 23 | + print("El email \(email) no es válido.") |
| 24 | + } |
| 25 | +} |
| 26 | + |
| 27 | +func phoneValidation(_ phone: String) { |
| 28 | + let pattern = #"^\+?(\d{2,3})?[-. ]?\d{9}$"# |
| 29 | + let regex = try! NSRegularExpression(pattern: pattern) |
| 30 | + if regex.firstMatch(in: phone, options: [], range: NSRange(location: 0, length: phone.utf16.count)) != nil { |
| 31 | + print("El teléfono \(phone) es válido.") |
| 32 | + } else { |
| 33 | + print("El teléfono \(phone) no es válido.") |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +func urlValidation(_ url: String) { |
| 38 | + let pattern = #"^(http|https)://[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}"# |
| 39 | + let regex = try! NSRegularExpression(pattern: pattern) |
| 40 | + if regex.firstMatch(in: url, options: [], range: NSRange(location: 0, length: url.utf16.count)) != nil { |
| 41 | + print("La URL \(url) es válida.") |
| 42 | + } else { |
| 43 | + print("La URL \(url) no es válida.") |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +let texto = "Este es un texto con números como 123, 45.6, -7 y 1000." |
| 48 | +print("Vamos a analizar el siguiente texto:") |
| 49 | +print("'\(texto)'\n") |
| 50 | +regExpr(texto) |
| 51 | + |
| 52 | +let texto2 = "123Erase una vez un número 1234567890 y otro 0987654321. Y para terminar456" |
| 53 | +print("Vamos a analizar el siguiente texto:") |
| 54 | +print("'\(texto2)'\n") |
| 55 | +regExpr(texto2) |
| 56 | + |
| 57 | +emailValidation("correo@correo.com") |
| 58 | +emailValidation("correo@correo") |
| 59 | + |
| 60 | +phoneValidation("+34 123456789") |
| 61 | +phoneValidation("123456789") |
| 62 | + |
| 63 | +urlValidation("http://www.google.com") |
| 64 | +urlValidation("www.google.com") |
0 commit comments