我需要在格式化字符串后删除下划线的帮助

时间:2019-07-04 11:48:27

标签: swift swift4 nsattributedstring

当字符串以下划线开头和结尾时,我将其设为斜体。之后,我要删除下划线。如果字符串是这样的"_hello_ world"

但是,这=> "_hello_ world _happy_"不起作用

这是我的正则表达式=> "\\_(.*?)\\_"

func applyItalicFormat(string: String) {
        let matches = RegexPattern.italicRegex.matches(string)
        for match in matches {
            let mRange = match.range
            self.addAttributes([NSAttributedStringKey.font : UIFont.latoMediumItalic(size: 15)],
                               range: mRange)

            if let rangeObj = Range(NSMakeRange(mRange.location, mRange.upperBound), in: string) {
                var sub = string.substring(with: rangeObj)
                sub = sub.replacingOccurrences(of: "_", with: "")

                print("sub is \(sub)")

                replaceCharacters(in: mRange, with: sub)
            } else {

            }
        }
    }

2 个答案:

答案 0 :(得分:1)

另一种正则表达式格式listToArray()并使用function arrayToList (array) { return array.reduceRight( (rest, value) => ({ value, rest }), null ); } function listToArray (list, array = []) { return list ? listToArray(list.rest, [...array, list.value]) : array; } const list = arrayToList([10, 20, 30]); const array = listToArray(list); console.log(list); console.log(array);

\\_(?:(?!_).)+\\_

屏幕截图

enter image description here

答案 1 :(得分:0)

稍作修改,并使用range(at:)个匹配项:

extension NSMutableAttributedString {
    func applyItalicFormat(pattern: String) {
        let regex = try! NSRegularExpression(pattern: pattern, options: [])
        let matches = regex.matches(in: string, options: [], range: NSRange(location: 0, length: string.utf16.count))
        let italicAttributes = [NSAttributedString.Key.font: UIFont.italicSystemFont(ofSize: 15)]
        for match in matches.reversed() {
            let textRange = match.range(at: 1)
            let attributedTextToChange = NSMutableAttributedString(attributedString: self.attributedSubstring(from: textRange))
            attributedTextToChange.addAttributes(italicAttributes, range: NSRange(location: 0, length: attributedTextToChange.length))
            replaceCharacters(in: match.range, with: attributedTextToChange)
        }
    }
}

您不需要替换_,因为您已经拥有足够的文本范围而没有下划线。
我使用matches.reversed(),因为当您应用第一个时,那么已经找到的第二个的范围不再正确(您删除了两次_)。
我更喜欢提取attributedString部分以进行修改,修改,然后将其替换为修改后的部分。 我简化了其余的代码。

样本测试(可在操场上使用):

let initialTexts = ["_hello_ world", "\n\n", "_hello_ world _happy_"]
let label = UILabel.init(frame: CGRect(x: 0, y: 0, width: 500, height: 500))
label.backgroundColor = .orange
label.numberOfLines = 0

let attr = NSMutableAttributedString()

for anInitialText in initialTexts {
    let attributedStr = NSMutableAttributedString(string: anInitialText)
    attributedStr.applyItalicFormat(pattern: "\\_(.*?)\\_")
    attr.append(attributedStr)
}

label.attributedText = attr
相关问题