Home > Software engineering >  how do I properly escape this regex string in swift to create a NSRegularExpression object?
how do I properly escape this regex string in swift to create a NSRegularExpression object?

Time:09-27

the google maps API says to use this regex to find a valid google maps link, I can't seem to create a regex object with this string without it throwing an error, I have tried removing the backslashes but it still comes back as invalid

(http(s?)://)?
((maps\.google\.{TLD}/)|
 ((www\.)?google\.{TLD}/maps/)|
 (goo.gl/maps/))
.*

e.g.

do {
    let regex = try NSRegularExpression(pattern: "(http(s?)://)?((maps.google.{TLD}/)|((www.)?google.{TLD}/maps/)|(goo.gl/maps/)).*")
} catch {
    print(error)
}

CodePudding user response:

The backslashes are crucial. A period without a backslash means any character. You have to add a second backslash respectively but there is a convenience syntax:

Wrap the literal string in #: (#" ... "#)

do {
    let regex = try NSRegularExpression(pattern: #"(http(s?)://)?((maps\.google\.{TLD}/)|((www\.)?google\.{TLD}/maps/)|(goo.gl/maps/)).*"#)
} catch {
    print(error)
}

CodePudding user response:

You should not remove backslashes, you should double them. And then you should also escape { and } since it reads them as quantifiers.

This gives:

(http(s?)://)?((maps\\.google\\.\\{TLD\\}/)|((www\\.)?google\\.\\{TLD\\}/maps/|(goo.gl/maps/)).*
  • Related