You need to replace the whole match with the $1
replacement backreference that holds the contents captured with the first capturing group.
Besides, I'd advise to write the [\d]
as \d
to avoid misinterpretations of the character class unions if you decide to expand the pattern later. Also, it is safer to use .*?
, lazy dot matching, to get to the first ]
rather than to the last ]
(if you use .*
greedy variation). However, that depends on the real requirements.
Use either of the following:
let txt = "Lorem ipsum @[1484987415095898:274:Page Four] dolores"
let regex = NSRegularExpression(pattern: "@\\[\\d+:\\d+:(.*?)\\]", options:nil, error: nil)
let newString = regex!.stringByReplacingMatchesInString(txt, options: nil, range: NSMakeRange(0, count(txt)), withTemplate: "$1")
print(newString)
// => Lorem ipsum Page Four dolores
or
let txt = "Lorem ipsum @[1484987415095898:274:Page Four] dolores"
let newString = txt.replacingOccurrences(of: "@\\[\\d+:\\d+:(.*?)]", with: "$1", options: .regularExpression)
print(newString)
// => Lorem ipsum Page Four dolores