3

The regex I'm using in my application is a combination of user-input and code. Because I don't want to restrict the user I would like to escape all regex-relevant characters like "+", brackets , slashes etc. from the entry. Is there a function for that or at least an easy way to get all those characters in an array so that I can do something like this:

for regexChar in regexCharacterArray{
    myCombinedRegex = myCombinedRegex.replaceOccurences(of: regexChar, with: "\\" + regexChar)
}
LarsGvB
  • 267
  • 3
  • 11

1 Answers1

6

Yes, there is NSRegularExpression.escapedPattern(for:):

Returns a string by adding backslash escapes as necessary to protect any characters that would match as pattern metacharacters.

Example:

let escaped = NSRegularExpression.escapedPattern(for: "[*]+")
print(escaped) // \[\*]\+
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • so I would insert the string i would like to have the regex-characters escaped in as the `for:`-value ? – LarsGvB Mar 27 '18 at 15:31
  • 1
    @LarsGvB: Yes, exactly. – Martin R Mar 27 '18 at 15:32
  • I expected the output to be `\[\*\]\+` (note the back slash before `]`) – Soc Jan 05 '21 at 22:02
  • @Soc: No, you don't have to escape a closing square bracket. It has no special meaning if it does not follow an (unescaped) opening square bracket. – Martin R Jan 05 '21 at 22:05
  • Understood. In my use case I was trying to use the escaped expression inside square brackets i.e. `"[\(escaped)]"`. I ended up having to replace `]` with `\]` on the escaped sequence for this to work. – Soc Jan 12 '21 at 17:46