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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With