Swift正则表达式和反斜杠

时间:2014-08-22 05:11:41

标签: ios regex swift

在我正在开发的应用程序中,我从Plist文件中读取了一系列正则表达式。

当我尝试应用以下表达式时出现问题:  \\(x\h{2}|[0-2][0-7]{,2}|3[0-6][0-7]?|37[0-7]?|[4-7][0-7]?|.)

我收到错误:

"Error Domain=NSCocoaErrorDomain Code=2048 \"The operation couldn’t be completed. (Cocoa error 2048.)\" UserInfo=0x7fc862ea7220 {NSInvalidValue=\\\\(x\\h{2}|[0-2][0-7]{,2}|3[0-6][0-7]?|37[0-7]?|[4-7][0-7]?|.)}"

似乎反斜杠字符被转义。我尝试使用以下代码来取消它们,但没有成功:

var match: String // an instance variable, just here for the purpose of the example

if let input = regularExpressions[n] as? NSString {

    var convertedString = input.mutableCopy() as NSMutableString

    let transform = "Any-Hex/Java"
    CFStringTransform(convertedString, nil, transform as NSString, 1)

    self.match = convertedString

}

任何线索?

1 个答案:

答案 0 :(得分:0)

至少在Objective-C中,你的正则表达式中的任何反斜杠都必须被转义,所以你的模式:

\\(x\h{2}|[0-2][0-7]{,2}|3[0-6][0-7]?|37[0-7]?|[4-7][0-7]?|.)

应该是

\\(x\\h{2}|[0-2][0-7]{,2}|3[0-6][0-7]?|37[0-7]?|[4-7][0-7]?|.)