我试图通过这段代码 (Swift 3.0) 将 hello_world
更改为 helloWorld
:
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
中的替换模板模式替换大写字符串。
最佳答案
处理您的案例的一种方法是子类化 NSRegularExpression
并覆盖 replacementString(for:in:offset:template:)
方法。
class ToUpperRegex: NSRegularExpression {
override func replacementString(for result: NSTextCheckingResult, in string: String, offset: Int, template templ: String) -> String {
guard result.numberOfRanges > 2 else {
return ""
}
let matchingString = (string as NSString).substring(with: result.rangeAt(2)) as String
return matchingString.uppercased()
}
}
let oldLine = "hello_world"
let fullRange = NSRange(0..<oldLine.utf16.count) //<-
let tuRegex = try! ToUpperRegex(pattern: "(_)(\\w)")
let newLine = tuRegex.stringByReplacingMatches(in: oldLine, range: fullRange, withTemplate: "")
print(newLine) //->helloWorld
关于regex - 如何在 Swift 中用 NSRegularExpression 替换大写字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40298831/