Replace regex string in swift

I want to replace the part of the string that matches the regex pattern.

I have the following regex pattern:

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

And this is the string replacement pattern:

 $1@hoge \.$2 

How can I use them inside Swift code?

+5
source share
1 answer

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

Here is a snippet showing how to use it:

 let txt = " myname@test.com " 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) 

Please note that I changed the regex to

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

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

+6
source

All Articles