2016-10-28 29 views
2

我是想通過這個代碼片段(雨燕3.0)來改變hello_worldhelloWorld如何在Swift中用NSRegularExpression替換大寫字符串?

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中的替換模板模式替換大寫字符串。

+0

SublimeText使用支持'\ L'運算符的Boost正則表達式。 Swift使用ICU,它不支持案件chahging操作員。 –

+0

@WiktorStribiżew所以'NSRegularExpression'支持替換模板中的'$ num'以外的其他東西嗎? –

+0

反斜槓也是ICU正則表達式替換模式中的特殊字符,請參閱[* ICU用戶指南:替換文本*](http://www.icu-project.org/userguide/regexp)。 –

回答

1

的一種方式一起工作你的情況是繼承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 
0

這不回答這個問題屬於正則表達式,但可能是對讀者不一定需要使用正則表達式來執行此任務的興趣(更確切地說,使用本地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 
相關問題