I was trying to change hello_world
to helloWorld
by this snippet of code (Swift 3.0):
import Foundation
let oldLine = "hello_world"
let fullRange = NSRange(location: 0, length: oldLine.characters.count)
let newLine = NSMutableString(string: oldLine)
let regex = try! NSRegularExpression(pattern: "(_)(\\w)", options: [])
regex.replaceMatches(in: newLine, options: [], range: fullRange,
withTemplate: "\\L$2")
The result was newLine = "helloLworld"
I used "\\L$2"
as template because I saw this answer: https://stackoverflow.com/a/20742304/5282792 saying \L$2
is the pattern for the second group's uppercase in replacement template. But it didn't work in NSRegularExpression
.
So can I replace a string with its uppercase with a replacement template pattern in NSRegularExpression
.
One way to work with your case is subclassing
NSRegularExpression
and overridereplacementString(for:in:offset:template:)
method.This doesn't answer the question pertaining regex, but might be of interest for readers not necessarily needing to use regex to perform this task (rather, using native Swift)