2014-10-08 32 views
1

當我使用下面的代碼剝離http://www.掀起了URL的開始,我得到一個錯誤。爲什麼我的Swift中的正則表達式不能編譯?我如何給它一個可變的字符串呢?

var error: NSError? = nil 
let regex = NSRegularExpression(pattern: "^(http(s)?://)?(www(\\d)?\\.)?", options: nil, error: &error) 

var stringy = "http://www.google.com/" 
regex.replaceMatchesInString(stringy, options: nil, range: NSMakeRange(0, countElements(stringy)), withTemplate: "") 

錯誤時正在:

'的NSString' 不是 '的NSMutableString'

如何解決這個亞型?我究竟做錯了什麼?

+0

[* * * * replaceMatcehsInString'工作](https://developer.apple.com/library/mac/documentation/Foundation/Reference/NSRegularExpression_Class/Reference/Reference.html#//apple_ref/occ/instm/NSRegularExpression/replaceMatchesInString:選項:範圍:withTemplate :)?爲什麼它*不接受不可變的字符串?它與「正則表達式[..]不編譯」無關。與'stringByReplacingMatchesInString'比較。 – user2864740 2014-10-08 01:23:44

回答

3

你可以通過簡單地使用NSMutableString(string: ...)構造stringyNSMutableString。您還需要執行其他一些操作才能使代碼正常工作:

  1. 您無法通過nil獲取選項。如果你不希望傳遞的任何選項,正確的值是NSMatchingOptions.allZeros
  2. 在Xcode的6.1 GM,您使用的是NSRegularExpressioninit方法返回一個可選(NSRegularExpression?),所以你需要使用可選的鏈接來致電regex?.replaceMatchesInString。 (這可能不是Xcode 6.0.1中的情況;我不確定何時做出更改)
  3. 由於stringy現在是NSMutableString,因此您不能對其調用countElements()。只需使用NSString的length屬性即可。

有了這些變化,代碼如下:

var error: NSError? = nil 
let regex = NSRegularExpression(pattern: "^(http(s)?://)?(www(\\d)?\\.)?", 
    options: nil, error: &error) 

var stringy = NSMutableString(string: "http://www.google.com") 
regex?.replaceMatchesInString(stringy, options: NSMatchingOptions.allZeros, 
    range: NSMakeRange(0, stringy.length), withTemplate: "") 

然後調用println(stringy)它執行後輸出:

google.com

+0

由於Swift 2.2#1需要'[]'而不是'NSMatchingOptions.allZeros'或'nil'。 – LinusGeffarth 2016-04-22 15:58:27

2

讓我知道如果這讓你想要的地方:

let oldString = "http://www.google.com/" 

let newString = oldString.stringByReplacingOccurrencesOfString("^(http(s)?://)?(www(\\d)?\\.)?", withString:"" as NSString, options:NSStringCompareOptions.RegularExpressionSearch, range:nil) 
println(newString) // google.com/ 
+0

+1,在這裏工作,比用'NSRegularExpression'做得更好。 – Houssni 2014-11-03 14:46:47

相關問題