```swift import Foundation
let pattern = "cat" let replacement = "dog" let text = "I have a cat and another cat."
do { let regex = try NSRegularExpression(pattern: pattern) let modifiedText = regex.stringByReplacingMatches(in: text, options: [], range: NSRange(location: 0, length: text.utf16.count), withTemplate: replacement) print(modifiedText) // 输出:I have a dog and another dog. } catch { print("正则表达式错误: (error.localizedDescription)") } ```
2.3 提取信息
```swift import Foundation
let text = "My phone numbers are (123) 456-7890 and (098) 765-4321." let pattern = "\(\d{3}\) \d{3}-\d{4}"
do { let regex = try NSRegularExpression(pattern: pattern) let matches = regex.matches(in: text, options: [], range: NSRange(location: 0, length: text.utf16.count))
for match in matches {
let matchRange = match.range
let phoneNumber = (text as NSString).substring(with: matchRange)
```swift import Foundation
let text = "John Doe (john@example.com)" let pattern = "(\w+) (\w+) \(([^)]+)\)"
do { let regex = try NSRegularExpression(pattern: pattern) let matches = regex.matches(in: text, options: [], range: NSRange(location: 0, length: text.utf16.count))
for match in matches {
let firstName = (text as NSString).substring(with: match.range(at: 1))
let lastName = (text as NSString).substring(with: match.range(at: 2))
let email = (text as NSString).substring(with: match.range(at: 3))
```swift import Foundation
let text = "hello world 123" let pattern = "(?:hello|hi) (\w+) (\d+)"
do { let regex = try NSRegularExpression(pattern: pattern) let matches = regex.matches(in: text, options: [], range: NSRange(location: 0, length: text.utf16.count))
for match in matches {
let name = (text as NSString).substring(with: match.range(at: 1))
let number = (text as NSString).substring(with: match.range(at: 2))
```swift import Foundation
let text = "dog cat dogfish" let pattern = "dog(?!fish)"
do { let regex = try NSRegularExpression(pattern: pattern) let matches = regex.matches(in: text, options: [], range: NSRange(location: 0, length: text.utf16.count))
for match in matches {
let matchedText = (text as NSString).substring(with: match.range)