正则表达式

正则表达式

说简单也简单, 说复杂当然也有复杂的用法
简单的说: 是记录文本规则的代码
复杂的说: 真对字符串的一门语言

上面都在扯蛋

匹配 不包含 某些字段 的正则
参考博客
stack overflow

^((?!hede).)*$

/^(?!.*?hede).*$/

关键字

简单的话, 其实就是他的一些关键字和你想要匹配的字符之间的使用

想好好了解的话, 网上很多教程了, 多写一篇也是累赘, 没必要浪费时间.
这里我感觉比较不错的帖子
看这个就行了.

下面就是我在学习中自己记录的一些注意点和应用点了~

使用:

\b: 标记单词的开始和结尾的分隔

更换某些文字时, 可以使用 sublime 来测试正则匹配的情况, 甚至在正则替换后将内容粘贴到需要的地方去, 省去很多时间

1
2
3
4
5
6
7
8
9
10
11
12

UI Intl
('.*'),(.*)employment.(\w+) &(.*)}
('.*'),(.*)employment.(\w+) [&|](.*)}
this.intlMsg('$3'),$2employment.$3 &$4}



intl message:

.*'(.*)',(.*)employment.(\w+) (&&|).*
$3: {\n\t\tid: 'employment.$3',\n\t\tdefaultMessage: '$1@',\n},

关于Swift 使用正则

有些时候 Swift 中, NSRegularExpression这个类会接收一个StringSwift 类型, 但是其内部仍然是使用NSString, 所使用的 Range 也是根据 NSString 来计算获取的, 不是 SwiftString 的长度.

Swift4 中, 其标准库提供了一个函数来转换R Range<String.Index>NSRange

虽然不常使用, 但是避免不了有时候会去验证某些字符串. 我们可以定义一下方法
我们可以定义一个用作匹配的函数:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
//  Swift4
func matches(for regex: String, in text: String) -> [String] {

do {
// 生成正则匹配规则
let regex = try NSRegularExpression(pattern: regex)
// 匹配字符串, 传入目标字符串和一个范围, 返回一个 range 的集合
let results = regex.matches(in: text,
range: NSRange(text.startIndex..., in: text))
return results.map {
// 通过 range 的转换, 拿出对应的字符串
String(text[Range($0.range, in: text)!])
}
// 注意: 对于`Range($0.range, in: text)!`的强制解包是安全的, 因为 NSRange 引用了传入的 text 的一个子串. 当然, 你想避免这样的话可以使用下面的来替换 return
// return results.flatMap {
// Range($0.range, in: text).map { String(text[$0]) }
// }
} catch let error {
print("invalid regex: \(error.localizedDescription)")
return []
}
}

// Swift3
func matches(for regex: String, in text: String) -> [String] {

do {
let regex = try NSRegularExpression(pattern: regex)
// 需要先转成 NSString 来获取正确的 Range
let nsString = text as NSString
let results = regex.matches(in: text,
range: NSRange(location: 0, length: nsString.length))
return results.map { nsString.substring(with: $0.range)}
} catch let error {
print("invalid regex: \(error.localizedDescription)")
return []
}
}

以上的验证 example:

1
2
3
4
let string = "🇩🇪€4€9"
let matched = matches(for: "[0-9]", in: string)
print(matched)
// ["4", "9"]

ref: Swift extract regex matches


为了方便我们也可以给正则表达式做一个封装

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
struct RegexHelper {
let regex: NSRegularExpression

init(_ pattern: String) throws {
try regex = NSRegularExpression(pattern: pattern,
options: .CaseInsensitive)
}

func match(input: String) -> Bool {
let matches = regex.matchesInString(input,
options: [],
range: NSMakeRange(0, input.utf16.count))
return matches.count > 0
}
}

可以这么使用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
let mailPattern =
"^([a-z0-9_\\.-]+)@([\\da-z\\.-]+)\\.([a-z\\.]{2,6})$"

let matcher: RegexHelper
do {
matcher = try RegexHelper(mailPattern)
}

let maybeMailAddress = "onev@onevcat.com"

if matcher.match(maybeMailAddress) {
print("有效的邮箱地址")
}
// 输出:
// 有效的邮箱地址

基于这个封装, 我们可以做一个方便的 operation 函数来方便之后的使用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
infix operator =~ {
associativity none
precedence 130
}

func =~(lhs: String, rhs: String) -> Bool {
do {
return try RegexHelper(rhs).match(lhs)
} catch _ {
return false
}
}

// 使用
if "onev@onevcat.com" =~
"^([a-z0-9_\\.-]+)@([\\da-z\\.-]+)\\.([a-z\\.]{2,6})$" {
print("有效的邮箱地址")
}
// 输出:
// 有效的邮箱地址

ref: 正则表达式