为什么我的线锚没有像我预期的那样工作?

Why is my line anchor not functioning as I expected?

我正在尝试解析 .ics 文件中的位置条目,如下图所示。通常这工作正常,即使我能找到的唯一测试器是 PCRE 而不是 ICU,因为我只需要为任何特殊字符添加一个额外的反斜杠。

但是在 swift 中我得到以下结果:

"^Location" //No Match
"^VERSION" //No Match
"^BEGIN" //Match
"^ :" //Match

我能否让“^”锚点像在 PCRE 测试仪中那样发挥作用?

PCRE 正则表达式测试器

代码

func testParticipantParsing()
{
    //let locationRegex = "^LOCATION:(.*(?:\n :?.*)*)"
    let locationRegex = "LOCATION:(.*(?:\n :?.*)*)"
    var regex : NSRegularExpression! = nil
    var resultsArray = [String]()

//Parse for location
    do
    {
        regex = try NSRegularExpression(pattern: locationRegex, options: NSRegularExpressionOptions.init(rawValue: 0))
        let nsString = content as NSString
        let results = regex.matchesInString(content, options: [], range: NSMakeRange(0, nsString.length))
        resultsArray = results.map{ nsString.substringWithRange([=11=].range) }
    }
    //Catch errors if regex fails
    catch
    {
        print("invalid regex")
    }
    //Strip .ics new line tokens
    for var result in resultsArray
    {
        result = result.stringByReplacingOccurrencesOfString("\n :", withString: "")
        result = result.stringByReplacingOccurrencesOfString("\n ", withString: "")
        print(result)
    }
}

只需在您的模式开头添加 (?m)

let locationRegex = "(?m)^LOCATION:(.*(?:\n :?.*)*)"
                     ^^^^

(?m) 是 MULTILINE 修饰符的内联修饰符版本,它强制 ^ 匹配 line 开头的位置,而不是 string(并使 $ 匹配行尾,换行序列之前的位置)。

Table 4: Flag Options:

m flag:
Control the behavior of ^ and $ in a pattern. By default these will only match at the start and end, respectively, of the input text. If this flag is set, ^ and $ will also match at the start and end of each line within the input text.