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

后端 未结 2 1774
南方客
南方客 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:15

    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)

    extension String {
        func camelCased(givenSeparators separators: [Character]) -> String {
            let charChunks = characters.split { separators.contains($0) }
            guard let firstChunk = charChunks.first else { return self }
            return String(firstChunk).lowercased() + charChunks.dropFirst()
                .map { String($0).onlyFirstCharacterUppercased }.joined()
        }
    
        // helper (uppercase first char, lowercase rest)
        var onlyFirstCharacterUppercased: String {
            let chars = characters
            guard let firstChar = chars.first else { return self }
            return String(firstChar).uppercased() + String(chars.dropFirst()).lowercased()
        }
    }
    
    /* Example usage */
    let oldLine1 = "hello_world"
    let oldLine2 = "fOo_baR BAX BaZ_fOX"
    
    print(oldLine1.camelCased(givenSeparators: ["_"]))      // helloWorld
    print(oldLine2.camelCased(givenSeparators: ["_", " "])) // fooBarBazBazFox
    
    0 讨论(0)
  • 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..<oldLine.utf16.count) //<-
    let tuRegex = try! ToUpperRegex(pattern: "(_)(\\w)")
    let newLine = tuRegex.stringByReplacingMatches(in: oldLine, range: fullRange, withTemplate: "")
    print(newLine) //->helloWorld
    
    0 讨论(0)
提交回复
热议问题