Yoav Schwartz
Yoav Schwartz

Reputation: 2027

Replacing a string with a capture group in Swift 3

I have the following string: "@[1484987415095898:274:Page Four]" and I want to capture the name, so I wrote to following regexp @\[[\d]+:[\d]+:(.*)] It seems to be working, but now I am struggling to understand how to replace the previous string with the capture group one.
i.e
"Lorem ipsum @[1484987415095898:274:Page Four] dolores" ->
"Lorem ipsum Page Four dolores"

Note, I saw how to get the capture group out using this stack question however, how to I find the original string this was extracted from and replace it?

Upvotes: 6

Views: 4596

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626689

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

Upvotes: 9

Related Questions