Swift简单使用正则

昨天有个需求是这样的:用户在论坛编辑器编辑(都用过论坛吧?),内容是HTML格式的文本提交到服务器,iOS app从服务器得到json数据,包含这段HTML内容,要把这段HTML展示到Label上,结果Label显示的时候发现这段HTML里面指定了字体大小,导致显示很丑,于是想用正则替换里面的font标签。

找了一下github,似乎也没有特别多star的repo,而且平时也只是偶尔简单用一下正则替换而已,没必要又搞一个第三方到项目里,于是就自己简单写几个String的扩展方法,简单实用,不考虑效率,嘿嘿。

使用方法

假设有这段字符串:

var str = "<p><font size=\"6\"><img src=\"http://img.t.sinajs.cn/t35/style/images/common/face/ext/normal/0b/tootha_thumb.gif\">An <u>open standard for soun</u>d,<img src=\"http://img.t.sinajs.cn/t35/style/images/common/face/ext/normal/70/vw_thumb.gif\">&nbsp;interopera</font><font size=\"2\">ble JavaScr</font>ipt promises—by implementers, for implementers.</p>"
  • str中查找所有匹配pattern的结果:

    let findResultArr = str.regexFind(pattern: "</?font.*?>", options: .caseInsensitive)
    print(findResultArr)

    输出:["<font size=\"6\">", "</font>", "<font size=\"2\">", "</font>"]
  • str是否匹配pattern:

    let isMatch = str.regexMatch(pattern: "</?font.*?>")
    print(isMatch)
    输出:true
  • 把str中所有font标签去掉:

    var woFont = str.regexReplace(pattern: "</?font.*?>", with: "")
    print(woFont)

    输出:
    <p><img src="http://img.t.sinajs.cn/t35/style/images/common/face/ext/normal/0b/tootha_thumb.gif">
    An <u>open standard for soun</u>d,
    <img src="http://img.t.sinajs.cn/t35/style/images/common/face/ext/normal/70/vw_thumb.gif">&nbsp;
    interoperable JavaScript promises—by implementers, for implementers.</p>
  • 替换str中所有img标签中的图片链接:

    let newStr = str.regexReplace(pattern: "<img\\s*?src\\s*?=(.+?)>",
    with: "\"http://darkhandz.com/avatar.png\"", atGroupIndex: 1)
    print(newStr)

    输出:
    <p><font size="6"><img src="http://darkhandz.com/avatar.png">
    An <u>open standard for soun</u>d,
    <img src="http://darkhandz.com/avatar.png">&nbsp;
    interopera</font><font size="2">ble JavaScr</font>ipt promises—by implementers, for implementers.</p>

代码

import Foundation

// MARK: - String简单正则
extension String{
/// 正则替换, 用with替换匹配的第groupIndex组
func regexReplace(pattern: String, with: String, atGroupIndex index: Int = 0,
options: NSRegularExpression.Options = []) -> String {
var result = self as NSString
let regex = try! NSRegularExpression(pattern: pattern, options: options)
let res = regex.matches(in: self, options: [], range: NSMakeRange(0, self.characters.count))
for checkingRes in res.reversed() {
result = result.replacingCharacters(in: checkingRes.rangeAt(index), with: with) as NSString
}
return result as String
}

/// 正则查找,返回匹配结果数组,可以指定返回匹配的第groupIndex组
func regexFind(pattern: String, atGroupIndex index: Int = 0, options: NSRegularExpression.Options = []) -> [String] {
var result = [String]()
let regex = try! NSRegularExpression(pattern: pattern, options: options)
regex.enumerateMatches(in: self, options: [], range: NSMakeRange(0, self.characters.count)) {
(checkingRes, flag, shouldStop) in
let substr = (self as NSString).substring(with: checkingRes!.rangeAt(index))
result.append(substr)
}
return result
}

/// 正则匹配,是否匹配pattern
func regexMatch(pattern: String, options: NSRegularExpression.Options = []) -> Bool {
let regex = try! NSRegularExpression(pattern: pattern, options: options)
let count = regex.numberOfMatches(in: self, options: [], range: NSMakeRange(0, self.characters.count))
return count > 0
}
}