我是想通過這個代碼片段(雨燕3.0)來改變hello_world
到helloWorld
:如何在Swift中用NSRegularExpression替換大寫字符串?
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")
的結果newLine = "helloLworld"
我用"\\L$2"
作爲模板,因爲我看到了這樣的回答:https://stackoverflow.com/a/20742304/5282792說\L$2
是替換模板中第二組的大寫模式。但它在NSRegularExpression
中不起作用。
那麼我可以使用NSRegularExpression
中的替換模板模式替換大寫字符串。
SublimeText使用支持'\ L'運算符的Boost正則表達式。 Swift使用ICU,它不支持案件chahging操作員。 –
@WiktorStribiżew所以'NSRegularExpression'支持替換模板中的'$ num'以外的其他東西嗎? –
反斜槓也是ICU正則表達式替換模式中的特殊字符,請參閱[* ICU用戶指南:替換文本*](http://www.icu-project.org/userguide/regexp)。 –