regex - Replacing a string with a capture group in Swift 3 -


i have following string: "@[1484987415095898:274:page four]" , want capture name, wrote following regexp @\[[\d]+:[\d]+:(.*)] seems working, struggling understand how replace previous string capture group one.
i.e
"lorem ipsum @[1484987415095898:274:page four] dolores" ->
"lorem ipsum page 4 dolores"

note, saw how capture group out using this stack question however, how find original string extracted , replace it?

you need replace whole match $1 replacement backreference holds contents captured first capturing group.

besides, i'd advise write [\d] \d avoid misinterpretations of character class unions if decide expand pattern later. also, safer use .*?, lazy dot matching, first ] rather last ] (if use .* greedy variation). however, depends on real requirements.

use either of 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 4 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 4 dolores 

Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -