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

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

提交回复
热议问题