Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 458
WalterBeiter Avatar asked Feb 02 '26 23:02

WalterBeiter


1 Answers

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.

like image 72
Wiktor Stribiżew Avatar answered Feb 04 '26 16:02

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!