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 卡仕达联发科大#hello #122dd"
let regex2 = Regex {
Capture {
One("#")
OneOrMore {
//1、字母或数字
.word
// 2、字母或数字
// ChoiceOf {//相当于或
// CharacterClass.letters//字母
// CharacterClass.digit//数字
// }
}
}
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 精确匹配出现一次
- OneOrMore 匹配出现一次或多次
- ZeroOrMore 匹配出现零次或一次
- Lookahead 仅当其内容在给定位置匹配时才允许匹配继续
- NegativeLookahead 仅当其内容在给定位置不匹配时才允许继续匹配
- Repeat 指定次数的匹配
其中可输入的常用参数有:
- .any 与任何元素匹配的字符类
- .anyNonNewline 与任何非换行符元素匹配的字符类
- .digit 任意数字
- .hexDigit 任何十六进制数字
- .word 任何单词字符
- .whitespace 任何空格字符