0

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!

Kex
  • 8,023
  • 9
  • 56
  • 129
  • You want string between `\n` or two `\n\n` because two`\n\n` occur only once. – Nirav D Aug 30 '16 at 04:40
  • Strictly spoken in your sample string there is no string *enclosed* in two linefeed characters. By the way: Declaring the parameters as implicit unwrapped optionals is nonsense in this case. – vadian Aug 30 '16 at 04:42
  • @vadian you're right. question edited. – Kex Aug 30 '16 at 04:52
  • @vadian: With respect to the IUOs: I might be to blame for that. The function (as originally posted in this question) is what I answered here http://stackoverflow.com/a/27880748/1187415, where I copied the IUOs from the question without thinking about it. Or maybe there was a reason in Swift 1.2, I don't remember. Anyway, I have fixed that now. – Martin R Aug 30 '16 at 05:24

1 Answers1

2

The primary issue I see is the regex pattern should include a capture group to select the multiple strings needed.

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")
Lightbeard
  • 4,011
  • 10
  • 49
  • 59
  • I updated my example. I had misread your question thinking you were using literal `\n` characters instead of new lines. I think the update will help. – Lightbeard Aug 30 '16 at 13:51