Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace string with regex in swift

Tags:

regex

swift

I want to replace a portion of a string that matches a regex pattern.

I have the following regex pattern:

(.+?)@test\.(.+?)

And this is a string replacement pattern:

$1@hoge\.$2

How can I use them inside Swift code?

like image 353
naohide_a Avatar asked Sep 16 '15 10:09

naohide_a


1 Answers

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

Here is a snippet showing how to use it:

let txt = "[email protected]"
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")
println(newString)

Swift 4.2 update:

let txt = "[email protected]"
let regex = "([^@\\s]+)@test\\.(\\w+)"
let repl = "$1@hoge.$2"
print( txt.replacingOccurrences(of: regex, with: repl, options: [.regularExpression]) )

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.

like image 85
Wiktor Stribiżew Avatar answered Nov 05 '22 16:11

Wiktor Stribiżew