Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing a string with a capture group in Swift 3

Tags:

regex

swift

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?

like image 496
Yoav Schwartz Avatar asked Sep 10 '17 20:09

Yoav Schwartz


1 Answers

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
like image 197
Wiktor Stribiżew Avatar answered Sep 29 '22 02:09

Wiktor Stribiżew