iOS 正则表达

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, p@p, 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”
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值