swift Swift提取正则表达式匹配
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了swift Swift提取正则表达式匹配相关的知识,希望对你有一定的参考价值。
> https://stackoverflow.com/a/40040472/10999568
```swift
extension String {
func matchingStrings(regex: String) -> [[String]] {
guard let regex = try? NSRegularExpression(pattern: regex, options: []) else { return [] }
let nsString = self as NSString
let results = regex.matches(in: self, options: [], range: NSMakeRange(0, nsString.length))
return results.map { result in
(0..<result.numberOfRanges).map {
result.range(at: $0).location != NSNotFound
? nsString.substring(with: result.range(at: $0))
: ""
}
}
}
}
```
## 大眾點評分享字串:
蒸的好海鲜馆,★★★★☆,¥246/人,蛇口海鲜,南海大道蛇口网谷万融大厦C座G层101http://m.dianping.com/appshare/shop/23995892
```swift
var regexed = theString.matchingStrings(regex:"^([^,]+),([^,]+),([^,]+),([^,]+),([^http]*)(.*)")
print(regexed)
```
**[["蒸的好海鲜馆,★★★★☆,¥246/人,蛇口海鲜,南海大道蛇口网谷万融大厦C座G层101http://m.dianping.com/appshare/shop/23995892", "蒸的好海鲜馆", "★★★★☆", "¥246/人", "蛇口海鲜", "南海大道蛇口网谷万融大厦C座G层101", "http://m.dianping.com/appshare/shop/23995892"]]**
```swift
if !regexed.isEmpty{
print("Name: \(regexed[0][1])")
print("Address: \(regexed[0][5])")
print("Url: \(regexed[0][6])")
}else{
print("regexed is Empty")
}
```
**Name: 蒸的好海鲜馆**
**Address: 南海大道蛇口网谷万融大厦C座G层101**
**Url: http://m.dianping.com/appshare/shop/23995892**
//Empty
以上是关于swift Swift提取正则表达式匹配的主要内容,如果未能解决你的问题,请参考以下文章
Swift 提取正则表达式匹配
Swift提取正则表达式匹配
Regex 正则表达式中几个符号([ ] ^ ?: ?= ?!)的概念
Swift 正则表达式匹配
无法让 Swift 中的正则表达式匹配“不包含”
如何检查我的字符串是不是与正则表达式匹配 - Swift 3 [重复]