Search code examples
swiftparsingtokenize

Swift String Tokenizer / Parser


Hello there fellow Swift devs!

I am a junior dev, and I'm trying to figure out a best way to tokenize / parse Swift String as an exercise.

What I have is a string which looks like this:

let string = "This is a {B}string{/B} and this is a substring."

What I would like to do is, tokenize the string, and change the "strings / tokens" inside the tags you see.

I can see using NSRegularExpression and it's matches, but it feels too generic. I would like to have only say 2 of these tags, that change the text. What would be the best approach in Swift 5.2^?

        if let regex = try? NSRegularExpression(pattern: "\\{[a-z0-9]+\}", options: .caseInsensitive) {
            let string = self as NSString
            return regex.matches(in: self, options: [], range: NSRange(location: 0, length: string.length)).map {
                // now $0 is the result? but it won't work for enclosing the tags :/ 
            }
        }

Solution

  • If the option of using html tags instead of {B}{/B} is acceptable, then you can use the StringEx library that I wrote for this purpose.

    You can select a substring inside the html tag and replace it with another string like this:

    let string = "This is a <b>string</b> and this is a substring."
    let ex = string.ex
    
    ex[.tag("b")].replace(with: "some value")
    
    print(ex.rawString) // This is a <b>some value</b> and this is a substring.
    print(ex.string) // This is a some value and this is a substring.
    

    if necessary, you can also style the selected substrings and get NSAttributedString:

    ex[.tag("b")].style([
        .font(.boldSystemFont(ofSize: 16)),
        .color(.black)
    ])
    
    myLabel.attributedText = ex.attributedString