Swift 提取 Regex 匹配
正則表達式(Regex)是一種用來匹配字符串模式的工具,它是編程中常用的工具之一。愛掏網 - it200.com在Swift中,我們可以使用NSRegularExpression
類來處理正則表達式的匹配。愛掏網 - it200.com
NSRegularExpression
是一個基于PCRE(Perl兼容正則表達式)引擎的Cocoa框架中的一個類,它可以用來處理正則表達式的匹配。愛掏網 - it200.com
以下是一個示例代碼,它演示了如何使用NSRegularExpression
來進行正則表達式的匹配:
let string = "Hello Swift Regex"
let pattern = "Swift"
do {
let regex = try NSRegularExpression(pattern: pattern)
let results = regex.matches(in: string, range: NSRange(string.startIndex..., in: string))
for match in results {
print("Matched range: \(match.range)")
let matchedString = String(string[Range(match.range, in: string)!])
print("Matched string: \(matchedString)")
}
} catch let error {
print("Invalid regular expression: \(error.localizedDescription)")
}
在上述代碼中,首先定義了一個字符串,然后定義了一個正則表達式Swift
。愛掏網 - it200.com接下來,我們利用NSRegularExpression
類以及上述正則表達式來進行匹配。愛掏網 - it200.com
代碼塊中第一步是實例化正則表達式,它的輸入是我們定義的正則表達式。愛掏網 - it200.com在這個例子中,我們使用了try
關鍵詞,這是因為NSRegularExpression的初始化代碼可能會拋出異常。愛掏網 - it200.com輸入參數中,我們使用了正則表達式的字符串形式。愛掏網 - it200.com后面兩個參數分別是要搜索的字符串及其范圍。愛掏網 - it200.com
接下來,我們使用matches(in:range:)
方法來獲取匹配結果,這個方法返回的是一個NSTextCheckingResult
類型的數組。愛掏網 - it200.com我們在for
循環中遍歷這個數組,從而逐個打印出每一個匹配項的位置以及具體匹配的字符串。愛掏網 - it200.com
提取匹配結果
在上述示例代碼中,我們利用NSRegularExpression
類對字符串模式進行了匹配,但是僅僅得到了匹配結果的位置信息,并未提取出具體的匹配結果。愛掏網 - it200.com接下來我們演示如何提取出匹配結果。愛掏網 - it200.com
let string = "Hello Swift Regex"
let pattern = "(Sw)(\\S*)"
do {
let regex = try NSRegularExpression(pattern: pattern)
let results = regex.matches(in: string, range: NSRange(string.startIndex..., in: string))
for match in results {
let matchedString = String(string[Range(match.range, in: string)!])
let group1Range = Range(match.range(at: 1), in: string)!
let group2Range = Range(match.range(at: 2), in: string)!
let group1String = String(string[group1Range])
let group2String = String(string[group2Range])
print("Matched string: \(matchedString)")
print("Group 1 string: \(group1String)")
print("Group 2 string: \(group2String)")
}
} catch let error {
print("Invalid regular expression: \(error.localizedDescription)")
}
在上面代碼的正則表達式"(Sw)(\\S*)"
中,括號將表達式的內容分成了兩個組:第一個組是"Sw"
,第二個組是"ift Regex"
。愛掏網 - it200.com
我們使用了matches(in:range:)
方法來獲取匹配結果,并使用NSTextCheckingResult
對象的range(at:)
方法來提取出組的位置信息。愛掏網 - it200.com我們還定義了兩個字符串group1String
和group2String
分別來表示分組1和分組2的具體匹配字符串,最后在循環中打印了所有的匹配結果。愛掏網 - it200.com
結論
在Swift中,我們可以使用NSRegularExpression
類來進行正則表達式的匹配及結果提取。愛掏網 - it200.com使用正則表達式需要熟練掌握匹配規則語法,以及掌握如何使用API進行匹配結果的處理。愛掏網 - it200.com通過應用上述示例代碼,開發者可以方便將匹配結果提取出來進行后續處理。愛掏網 - it200.com