naohide naohide - 3 years ago 88
Swift Question

Replace string with regex in swift

I want to replace a string using a regular expression in Swift.

I have the following regex pattern:


And this is a string replacement pattern:


How can I use them inside Swift code?

Answer Source

In Swift, you can use stringByReplacingMatchesInString for a regex-based replace.

Here is a snippet showing how to use it:

let txt = ""
let regex = NSRegularExpression(pattern: "([^@\\s]+)@test\\.(\\w+)", options:nil, error: nil)
let newString = regex!.stringByReplacingMatchesInString(txt, options: nil, range: NSMakeRange(0, count(txt)), withTemplate: "$1@hoge.$2")

Note that I changed the regex to

  • ([^@\\s]+) - matches 1 or more characters other than @ or whitespace
  • @ - matches @ literally
  • test\\.(\\w+) - matches test. literally and then 1 or more alphanumeric character (\w+).

Note that in the replacement string, you do not need to escape the period.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download