mjpablo23
mjpablo23

Reputation: 731

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).

Upvotes: 1

Views: 1091

Answers (2)

vadian
vadian

Reputation: 285069

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

Upvotes: 1

DonMag
DonMag

Reputation: 77433

Another approach --- IF you know the format of your string will be

fieldName1: \nfieldValue1\nfieldName2: \nfieldValue2\n etc

var str:String = "first name: \nkevin\nlast name:\nwilliams\nphone:\n212.555.1212"

var charsToClear = NSMutableCharacterSet(charactersIn: ":")
charsToClear.formUnion(with: .whitespaces)

let parts = str.components(separatedBy: "\n").map{ $0.trimmingCharacters(in: charsToClear as CharacterSet) }

This will split the string into an array of alternating fieldName and fieldValue. It will also trim extra whitespace and the colons on the way. So this example string would be turned into an array containing:

[ "first name", "kevin", "last name", "williams", "phone", "212.555.1212" ]

You could then create your attributed string(s) by stepping through the array, assigning any formatting you want.

As always, implement error checking as needed.

Upvotes: 0

Related Questions