regex - 如何在 Swift 中用 NSRegularExpression 替换大写字符串?

标签 regex swift

我试图通过这段代码 (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/

相关文章:

ios - 如何通过 Alamofire 和 SwiftyJSON 在 UIViewController 中使用根目录中的 JSON 对象

ios - 我正在尝试从一个屏幕到另一个屏幕重新创建表格 View ,但不断收到错误信号 sigabrt

ios - 在 UICollectionReusableView 中未调用委托(delegate)

java - 尝试用正则表达式匹配行

regex - 使用javascript显示不包括字符和空格的输入的正则表达式?

regex - 在记事本中使用正则表达式删除标签之间的文本

swift - J2ObjC with Swift - 归档时未找到桥接 header 导入

python - 搜索目录中的字符串

Python - 正则表达式以避免匹配重复项

ios - 脚本消息处理程序不工作