Search code examples
swiftregexline-breaksnegative-lookbehind

regex does not work in swift


I am using a regular expression to find all \n occurrences in a string.

The regular expression itself is working:

enter image description here

The expression finds \n but not \\n. Which is, what I want.

However, when I want to implement this in Swift for an iOS-application I get the error: invalid regex: The value „(?<!\)\n“ is invalid.

My code looks like this (after implementing the \ approach from the comments:

import UIKit

var str = "Hello, \n \\n playground"

let regex = try? NSRegularExpression(pattern: "(?<!\\\\)\\n", options: .caseInsensitive)

let matches = regex?.matches(in: str, options: .anchored, range: NSMakeRange(0, str.count))

print(matches)

matches is nil. It should find \n.


Solution

  • The regex is compiled with the .anchored option that requires the pattern to only match at the start of the string:

    Specifies that matches are limited to those at the start of the search range.

    You need to remove this option, e.g.

    let matches = regex?.matches(in: str, options: [], range: NSMakeRange(0, str.count))
    

    Note the "(?<!\\\\)\\n" string literal defines a (?<!\\)\n regex pattern that matches

    • (?<!\\) - a location in string that is not immediately preceded with a \ char
    • \n - a newline character, LF.

    See the regex demo online.