Swift正则表达式使用

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 任何空格字符
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容