如何解析字符串以将其转换为 nsattributedstring

How to parse a string in order to convert it to nsattributedstring

我有一个

形式的字符串

"@{profile: id1} is going to @{profile: id2}'s party"

如何将其转换为 nsattributedstring

"**Name1** is going to **Name2**'s party"

id1id2都代表一个字符串。 您可以通过将 id1 传递给名为 getName(by id: String)

的函数来获取 Name1

给定一个字符串

"@{profile: 735bcec0-1470-11e9-8384-a57f51e70e5f} is \
going to @{profile: 4c0bf620-2022-11e9-99ad-0777e9298bfb} party."

假设

getName(by: "735bcec0-1470-11e9-8384-a57f51e70e5f") -> "Jack"
getName(by: "4c0bf620-2022-11e9-99ad-0777e9298bfb") -> "Rose"

我想要取回一个 nsattributedstring

"Jack is going to Rose's party"

JackRose 都应该是粗体。

除了 NSMutableAttributedStringreplaceCharacters(in:with:) 方法外,您还可以使用正则表达式:

    //Prepare attributes for Normal and Bold
    let normalAttr: [NSAttributedString.Key: Any] = [
        .font: UIFont.systemFont(ofSize: 24.0)
    ]
    let boldAttr: [NSAttributedString.Key: Any] = [
        .font: UIFont.boldSystemFont(ofSize: 24.0)
    ]
    //Create an NSMutableAttributedString from your given string
    let givenString = """
    @{profile: 735bcec0-1470-11e9-8384-a57f51e70e5f} is \
    going to @{profile: 4c0bf620-2022-11e9-99ad-0777e9298bfb}'s party.
    """
    let attrString = NSMutableAttributedString(string: givenString, attributes: normalAttr)
    //Create a regex matching @{profile: id} with capturing id
    let pattern = "@\{profile:\s*([^}]+)\}"
    let regex = try! NSRegularExpression(pattern: pattern, options: [])
    let matches = regex.matches(in: givenString, range: NSRange(0..<givenString.utf16.count))
    //Iterate on matches in reversed order (to keep NSRanges consistent)
    for match in matches.reversed() {
        //Retrieve id from the first captured range
        let idRange = Range(match.range(at: 1), in: givenString)!
        let id = String(givenString[idRange])
        let name = getName(by: id)
        //Convert it to an NSAttributedString with bold attribute
        let boldName = NSAttributedString(string: name, attributes: boldAttr)
        //Replace the matching range with the bold name
        attrString.replaceCharacters(in: match.range, with: boldName)
    }