Swift Extract Regex Matches


In Swift, you can extract regex matches using the NSRegularExpression class provided by the Foundation framework. Swift's NSRegularExpression is a powerful tool for working with regular expressions in Swift. It can be used for a wide range of text-processing tasks.

NSRegularExpression Class

You can make use of regular expressions with the Swift Foundation framework class called NSRegularExpression. With the help of regular expressions, you may search and replace text as well as create patterns that define collections of strings.

You can use NSRegularExpression to convert a string pattern into a regular expression object, which you can then use to find and begin working with strings that match the pattern.

Here are Some of the Key Features of NSRegularExpression

  • Making a regular expression object − The init(pattern:options:) initializer may be used to make an NSRegularExpression object by giving a string pattern as a parameter. Regular expressions are described by a string known as a pattern.

  • Finding matches − You can look for matches in a string using the matches(in:options:range:) function once you have an NSRegularExpression object. An array of NSTextCheckingResult objects that detail the scope of each match is returned by this function.

  • Obtaining matching substrings − To obtain precise substrings that match the regular expression, you can use the Range and String classes. A customized string can be made from a specified range of characters using the Range class. This class defines a range of characters in a string.

  • Replacing matched substrings − You can use the

    stringByReplacingMatches(in:options:range:withTemplate:) method to replace specified substrings with a replacement string. The replacement string can contain special substitution patterns that reference the matched substrings.

Example 1: Find all Words with a Particular Length From a String

  • Step 1 − Create the input as a string that contains the text to be searched, and the pattern is a regular expression that matches any word that contains exactly five letters.

  • Step 2 − Use the try? operator to create an NSRegularExpression object with the given pattern, and if it fails, it returns nil.

  • Step 3 − Call the matches(in:range:) method of the NSRegularExpression class is then used to find all the matches in the input string.

  • Step 4 − Perform a loop that is used to extract the matching substrings using the Range and String classes.

  • Step 5 − The matchStrings array will contain all the substrings that match the regular expression pattern.

import Foundation
let inputString = "The quick brown fox jumps over the lazy dog."
let pattern = "\b\w{5}\b"
if let regex = try? NSRegularExpression(pattern: pattern) {
   let matches = regex.matches(in: inputString, range: NSRange(inputString.startIndex..., in: inputString))
   let matchStrings = matches.map { match in
      String(inputString[Range(match.range, in: inputString)!])
   }
   print("Input string: \(inputString)")
   print("Match strings: \(matchStrings)")
}

Output

Input string: The quick brown fox jumps over the lazy dog.
Match strings: ["quick", "brown", "jumps"]

Example 2: Find Email Addresses From a String

  • Step 1 − Create the input as a string that contains the text to be searched. The pattern is a regular expression that matches all email addresses.

  • Step 2 − Use the try? operator to create an NSRegularExpression object with the given pattern, and if it fails, it returns nil.

  • Step 3 − Call the matches(in:range:) method of the NSRegularExpression class is then used to find all the matches in the input string.

  • Step 4 − Perform a loop that is used to extract the matching substrings using the Range and String classes.

  • Step 5 − The matchStrings array will contain all the substrings that match the regular expression pattern.

import Foundation
let inputString = "Contact us at info@example.com or support@example.org"
let pattern = "[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}"
if let regex = try? NSRegularExpression(pattern: pattern) {
   let matches = regex.matches(in: inputString, range: NSRange(inputString.startIndex..., in: inputString))
   let matchStrings = matches.map { match in
      String(inputString[Range(match.range, in: inputString)!])
   }    
   print("Input string: \(inputString)")
   print("Match strings: \(matchStrings)")
}

Output

Input string: Contact us at info@example.com or support@example.org
Match strings: ["info@example.com", "support@example.org"]

This example shows how to extract all email addresses from a string using a regular expression. The pattern used is [A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}, which matches any string that has the format of an email address. This pattern matches any alphanumeric characters, dots, underscores, plus signs, and hyphens before the @ symbol, followed by a domain name that can contain dots and hyphens, and ends with a top-level domain that has at least two letters.

Example 3: Extract all Phone Numbers From a String

  • Step 1 − Create the input as a string that contains the text to be searched. The pattern is a regular expression that matches all the phone numbers.

  • Step 2 − Use the try? operator to create an NSRegularExpression object with the given pattern, and if it fails, it returns nil.

  • Step 3 − Call the matches(in:range:) method of the NSRegularExpression class is then used to find all the matches in the input string.

  • Step 4 − Perform a loop that is used to extract the matching substrings using the Range and String classes.

  • Step 5 − The matchStrings array will contain all the substrings that match the regular expression pattern.

import Foundation
let inputString = "Call us at (123) 456-7890 or (555) 123-4567"
let pattern = "\(\d{3}\) \d{3}-\d{4}"
if let regex = try? NSRegularExpression(pattern: pattern) {
   let matches = regex.matches(in: inputString, range: NSRange(inputString.startIndex..., in: inputString))
   let matchStrings = matches.map { match in
      String(inputString[Range(match.range, in: inputString)!])
   }
    
   print("Input string: \(inputString)")
   print("Match strings: \(matchStrings)")
}

Output

Input string: Call us at (123) 456-7890 or (555) 123-4567
Match strings: ["(123) 456-7890", "(555) 123-4567"]

This example shows how to extract all phone numbers from a string using a regular expression. The pattern used is \(\d{3}\) \d{3}-\d{4}, which matches any string that has the format of a phone number. This pattern matches any string that starts with an opening parenthesis, followed by three digits, then a closing parenthesis, a space, three digits, a hyphen, and finally four digits.

Conclusion

In Swift, regular expressions are an effective tool for handling text. You may construct and edit regular expressions using the NSRegularExpression class offered by the Foundation framework. Regular expressions can be used for tasks including finding and replacing text, extracting matching substrings, and verifying input. You may considerably enhance your proficiency working with text in Swift and advance as a programmer by studying regular expressions.

Updated on: 25-Apr-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements