Searching for strings starting with \n\n in Swift

时间:2016-08-30 04:31:25

标签: ios regex swift

Hey I have a requirement to increase the spacing in my UILables for double spaced line breaks. I want to search my string and find all the strings starting with \n\n. For example "Hello world\nI am on the next line\n\nNow I'm on the next line and it's spaced more than before\nNow I'm back to normal spacing". I'm having trouble trying to figure out the regex for this. I am trying:

let regExRule = "^\n\n*"

and passing it into this function:

func matchesForRegexInText(regex: String, text: String) -> [String] {

        do {
            let regex = try NSRegularExpression(pattern: regex, options: [])
            let nsString = text as NSString
            let results = regex.matchesInString(text,
                                                options: [], range: NSMakeRange(0, nsString.length))
            return results.map { nsString.substringWithRange($0.range)}
        } catch let error as NSError {
            print("invalid regex: \(error.localizedDescription)")
            return []
        }
    }

However I am getting an empty array. Not really sure how to construct the regex pattern for this. Any pointers would be really appreciated. Thanks!

1 个答案:

答案 0 :(得分:2)

我看到的主要问题是正则表达式模式应该包含一个捕获组来选择所需的多个字符串。

func matchesForRegexInText(regex : String, text: String) -> [String] {
    var captured = [String]()
    let exp = try! NSRegularExpression(pattern: regex, options: [])
    let matches = exp.matchesInString(text, options:[], range: NSMakeRange(0, text.characters.count))

    for match in matches {
        let c = (text as NSString).substringWithRange(match.rangeAtIndex(1))
        captured.append(c)
    }

    return captured
}

let re = "\\n\\n([\\w\\\\s,']+)"; // selection with (...)

// ["Alpha", "Bravo", "Charlie"]
let strResults = matchesForRegexInText(re, text: "\n\nAlpha\n\nBravo\n\nCharlie\n\n")
相关问题