11

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?

0

1 Answer 1

20

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.

Sign up to request clarification or add additional context in comments.

7 Comments

I wrote a RegEx replace method that takes a closure: eon.codes/blog/2017/08/03/regex-replace-with-closure
@GitSync I do not think the current problem needs to be solved with a closure enabled regex. Still, that can be of help to others, sure.
@WiktorStribiżew Totally agree that closure is overkill with this problem. But I couldn't find anything on stack or google about replacing with closures so I thought Id mention it.
@GitSync I think I have seen that somewhere. Maybe something similar. If I find it, I will post a comment.
@WiktorStribiżew My implementation isn't perfect. I think accumulatively appending a string is faster than inPlace substring replace. But I had to move on. I made a note of it in the code for a future improvement opportunity.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.