我在我的应用程序中使用的正则表达式是用户输入和代码的组合。因为我不想限制用户,所以我想从条目中转义所有与正则表达式相关的字符,如“+”、方括号、斜杠等。 是否有一个函数或至少有一种简单的方法来将所有这些字符放入一个数组中,以便我可以做这样的事情:
for regexChar in regexCharacterArray{
myCombinedRegex = myCombinedRegex.replaceOccurences(of: regexChar, with: "\\" + regexChar)
}
最佳答案
是的,有NSRegularExpression.escapedPattern(for:)
:
Returns a string by adding backslash escapes as necessary to protect any characters that would match as pattern metacharacters.
例子:
let escaped = NSRegularExpression.escapedPattern(for: "[*]+")
print(escaped) // \[\*]\+
关于swift - 是否有转义所有与正则表达式相关的字符的功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49516751/