Sobes.tech
Junior

What are regular expressions?

sobes.tech AI

Answer from AI

Regular expressions are a powerful tool for searching, replacing, and manipulating strings based on patterns. They are used to describe sets of strings using a compact syntax.

Main components of regular expressions:

  • Literals: Ordinary characters that match themselves (e.g., 'a', ',').
  • Metacharacters: Characters with special meanings, for example:
    • .: any character except a newline.
    • *: zero or more repetitions of the previous element.
    • +: one or more repetitions of the previous element.
    • ?: zero or one repetition of the previous element.
    • ^: start of the string.
    • $: end of the string.
    • []: character class (any of the characters inside the brackets).
    • |: or (alternative between patterns).
    • (): grouping.
  • Escape sequences: Combinations of characters starting with \ (e.g., \d for a digit, \s for a whitespace character).

In Swift, regular expressions are implemented using the NSRegularExpression class or the more modern Regex.

Example of using Regex in Swift:

// Find all digits in a string
let text = "Hello 123 World 456"
let regex = try? Regex("\\d+")

let matches = text.matches(of: regex!)
for match in matches {
    print("Found numbers: \(match.output)")
}

Regular expressions are widely used for input validation (e.g., email, phone numbers), data parsing from text, searching for specific substrings, and string formatting.