Search code examples
iosswift3nsattributedstringnsrange

swift 3 find range of text starting with newline and ending with :


I have a swift 3 string that looks like this:

var str:String = "first name: \nkevin\nlast name:\nwilliams"

when printed, it looks like this:

first name: 
kevin
last name:
williams
xxx field:
408 878 2125

I want to find the ranges of fields that start with "\n" and end with ":" so I can apply attributes to them. The field names may vary. For example, I could have "phone number:" or "address:" in other cases. how do I do this in swift 3?

an example is that I want to apply italics to the field names. so a result might be:

first name: kevin

last name: williams

xxx field: 408 878 2125

(The spaces after the colons got formatted out by stackoverflow).


Solution

  • A versatile and suitable solution is Regular Expression

    let string = "first name: \nkevin\nlast name:\nwilliams"
    
    let pattern = "\\n?(.*):"
    do {
        let regex = try NSRegularExpression(pattern: pattern)
        let matches = regex.matches(in: string, range: NSRange(string.startIndex..., in: string))
        for match in matches {
            let swiftRange = Range(match.rangeAt(1), in: string)!
            print(string[swiftRange])
        }
    } catch {
        print("Regex Error:", error)
    }
    

    Btw: The first entry does not start with \n