且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Swift - 从字符串中只获取字母数字字符

更新时间:2023-01-06 12:31:17

您可以直接使用 replacingOccurrences(从输入字符串中删除所有非重叠匹配项)和 [^A-Za-z0-9]+ 模式:

You may directly use replacingOccurrences (that removes all non-overlapping matches from the input string) with [^A-Za-z0-9]+ pattern:

let str = "_<$abc$>_"
let pattern = "[^A-Za-z0-9]+"
let result = str.replacingOccurrences(of: pattern, with: "", options: [.regularExpression])
print(result) // => abc

[^A-Za-z0-9]+ 模式是一个否定字符类,它匹配除类中定义的字符以外的任何字符,一个或多个出现次数(由于 + 量词).

The [^A-Za-z0-9]+ pattern is a negated character class that matches any char but the ones defined in the class, one or more occurrences (due to + quantifier).

查看正则表达式演示.