iOS 正則表達
阿新 • • 發佈:2021-02-18
public init(pattern: String, options: NSRegularExpression.Options = []) throws
NSRegularExpression的例項化方法,需要把匹配規則以字串的形式傳進去。像任何語言一樣,正則有自己的保留字元如下:
[] () . ? + * & ^ \ /
如果你想通過正則匹配這些特殊字元,那麼你需要通過backslash (反斜槓)去避開他。例如你想去搜索文本里面的.符號,那麼你的pattern就需要傳進去.
每一門語言在正則的基礎上有自己的細微調整,swift 和 OC 也一樣,iOS 的規則是在保留字元前新增\
func listMatches(for pattern: String, inString string: String) -> [String] { guard let regex = try? NSRegularExpression(pattern: pattern, options: []) else { return [] } let range = NSRange(string.startIndex..., in: string) let matches = regex.matches(in: string, options: [], range: range) return matches.map { let range = Range($0.range, in: string)! return String(string[range]) } }
匹配複數,3(pm|am) 可以匹配 3pm 3am,| 相當於 或運算
(Tom|Dick|Harry) 是可以匹配到的3個名字
如果你要在文字中捕獲 November,但是有人會用 Nov 表示 November,pattern 可以這樣 :Nov(ember)?
這個動作叫做捕獲,是因為他們能捕獲到匹配的內容,而且允許你在你的正則裡面引用他們,比如 你有一個字串 say hi to Harry ,如果你建立 搜尋 並替換 正則,用 that guy $1去替換匹配到的內容(Tom|Dick|Harry),那麼結果就是 say hi to that guy Harry. $1允許你去引用第一個匹配到的結果
字元集合表示匹配的字符合集,字符集出現在[]裡面。例如 t[aeiou] 匹配 ta te ti to tu.
[]也可以定義range,例如 搜尋100-109, 10[0-9] 這個等同於 10[0123456789] [a-f] 等同於 a b c d e f
字符集表示你想匹配的字元,如果你想篩選不想要的某個字元t[^o],那麼會匹配所有帶t的,除了to
. 匹配任意字元
. matches any character. p.p matches pop, pup, pmp, [email protected], and so on.
\W 匹配 字母 數字 下劃線,但是不包含標點符號 和其他的字元
hello\w will match “hello_” and “hello9” and “helloo” but not “hello!”
\d 匹配數字
[0-9]. \d\d?:\d\d will match strings in time format, such as “9:30” and “12:45”.
\b 匹配單詞邊界的字元,比如空格和標點
\b matches word boundary characters such as spaces and punctuation. to\b will match the “to” in “to the moon” and “to!”, but it will not match “tomorrow”. \b is handy for “whole word” type matching.
\S 匹配空格字元 space tab newline
\s matches whitespace characters such as spaces, tabs, and newlines. hello\s will match “hello ” in “Well, hello there!”.
^匹配一行的開始
^ matches at the beginning of a line. Note that this particular ^ is different from ^ inside of the square brackets! For example, ^Hello will match against the string “Hello there”, but not “He said Hello”.
$ 匹配一行的結束
$ matches at the end of a line. For example, the end$ will match against “It was the end” but not “the end was near”