How to replace a string with its uppercase with NSRegularExpression in Swift?

后端 未结 2 1773
南方客
南方客 2021-01-15 10:01

I was trying to change hello_world to helloWorld by this snippet of code (Swift 3.0):

import Foundation

let oldLine = \"hello_worl         


        
2条回答
  •  北恋
    北恋 (楼主)
    2021-01-15 10:32

    One way to work with your case is subclassing NSRegularExpression and override replacementString(for:in:offset:template:) method.

    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..helloWorld
    

提交回复
热议问题