1叹螟、通過設置Reference獲取匹配到的字段
import RegexBuilder
let str = "tome 123 joeal"
let regex = Regex {
Capture {
OneOrMore(.word)
}
OneOrMore(.whitespace)
Capture {
OneOrMore(.digit)
}
}
if let match = str.firstMatch(of: regex) {
let res = match.0
let res1 = match.1
let res2 = match.2
}
let numReference = Reference(Substring.self)
let regex1 = Regex {
OneOrMore(.word)
OneOrMore(.whitespace)
Capture(as: numReference) {
OneOrMore(.digit)
}
}
let match1 = str.matches(of: regex1)
match1.forEach { item in
debugPrint(item.output.0, item[numReference])
}
//控制臺打佣痢:"tome 123" "123"
2肌稻、匹配#xxx高亮字符
let str2 = "阿里卡達拉斯 #king adas打卡記錄快點放假啦收到 #work 卡仕達聯(lián)發(fā)科大#hello #122dd"
let regex2 = Regex {
Capture {
One("#")
OneOrMore {
//1、字母或數(shù)字
.word
// 2性誉、字母或數(shù)字
// ChoiceOf {//相當于或
// CharacterClass.letters//字母
// CharacterClass.digit//數(shù)字
// }
}
}
ZeroOrMore(.whitespace)
}
let match2 = str2.matches(of: regex2)
let res = match2.compactMap { item in
return item.output.1
}
debugPrint(res)
// 控制臺打印: ["#king", "#work", "#hello", "#122dd"]
以下是一些常用的:
- One 精確匹配出現(xiàn)一次
- OneOrMore 匹配出現(xiàn)一次或多次
- ZeroOrMore 匹配出現(xiàn)零次或一次
- Lookahead 僅當其內(nèi)容在給定位置匹配時才允許匹配繼續(xù)
- NegativeLookahead 僅當其內(nèi)容在給定位置不匹配時才允許繼續(xù)匹配
- Repeat 指定次數(shù)的匹配
其中可輸入的常用參數(shù)有:
- .any 與任何元素匹配的字符類
- .anyNonNewline 與任何非換行符元素匹配的字符類
- .digit 任意數(shù)字
- .hexDigit 任何十六進制數(shù)字
- .word 任何單詞字符
- .whitespace 任何空格字符