Replacing a string with a capture group in Swift 3

I have the following line: "@ [1484987415095898: 274: Page four]" and I want to write the name, so I wrote the following regexp @\[[\d]+:[\d]+:(.*)] It seems to work, but now I'm struggling to figure out how to replace the previous line with the capture group .

those. "Lorem ipsum @ [1484987415095898: 274: Page 4] dolores" →
  "Lorem ipsum Page 4 dolores"

Notice, I saw how to get the capture group using this question on the stack however, how can I find the original row that it extracted and replaced?

+4
source share
1 answer

$1 , , .

, [\d] \d, , . , .*?, lazy dot matching, ], ] ( .* ). .

:

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

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
+5

Source: https://habr.com/ru/post/1685402/


All Articles