I am using a regular expression to find all \n occurrences in a string.
The regular expression itself is working:

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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With