How to replace the characters !@#$%^*_+\= in a string using RegEx with Swift

1 Answer

0 votes
import Foundation

let str = "The!quick@brown#fox$jumps%^over*_the+\\lazy=dog."
let pattern = "[!@#$%^*_+=\\\\]"
let replacement = " "

// Perform regex replacement
let regex = try! NSRegularExpression(pattern: pattern)
let result = regex.stringByReplacingMatches(in: str, options: [], range: NSRange(location: 0, length: str.utf16.count), withTemplate: replacement)

print("Original: \(str)")
print("Modified: \(result)")



/*
run:

Original: The!quick@brown#fox$jumps%^over*_the+\lazy=dog.
Modified: The quick brown fox jumps  over  the  lazy dog.

*/

 



answered Jun 11, 2025 by avibootz
edited Jun 11, 2025 by avibootz
...