Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a function to escape all regex-relevant characters?

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)
}
like image 752
LarsGvB Avatar asked Nov 18 '25 20:11

LarsGvB


1 Answers

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) // \[\*]\+
like image 76
Martin R Avatar answered Nov 21 '25 10:11

Martin R



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!