ios - Replace regex match with attributed string and text -
our app api returns field custom format user mentions like: "this text mention @(steve|user_id)". before display on uitextview, need process text, find pattern , replace more user friendly. final result "this text mention @steve" @steve should have link attribute user_id. same functionality facebook.
first i've created uitextview extension, match function regex pattern.
extension uitextview { func processtext(pattern: string) { let instring = self.text let regex = try? nsregularexpression(pattern: pattern, options: []) let range = nsmakerange(0, instring.characters.count) let matches = (regex?.matchesinstring(instring, options: [], range: range))! [nstextcheckingresult] let attrstring = nsmutableattributedstring(string: instring, attributes:attrs) //iterate on regex matches match in matches { //properly print match range print(match.range) //a basic idea add link attribute on regex match range attrstring.addattribute(nslinkattributename, value: "\(schememap["@"]):\(must_be_user_id)", range: match.range) //still text it's in format @(steve|user_id) how replace @steve keeping link attribute ? } } } //to use let regex = ""\\@\\(([\\w\\s?]*)\\|([a-za-z0-9]{24})\\)"" mytextview.processtext(regex)
this have right now, i'm stucked trying final result
thanks lot !
i changed regex bit, got pretty result. modified code little well, can test directly in playgrounds.
func processtext() -> nsattributedstring { let pattern = "(@\\(([^|]*)([^@]*)\\))" let instring = "this text mention @(steve|user_id1) , @(alan|user_id2)." let regex = try? nsregularexpression(pattern: pattern, options: []) let range = nsmakerange(0, instring.characters.count) let matches = (regex?.matchesinstring(instring, options: [], range: range))! let attrstring = nsmutableattributedstring(string: instring, attributes:nil) print(matches.count) //iterate on regex matches match in matches.reverse() { //properly print match range print(match.range) //get username , userid let username = attrstring.attributedsubstringfromrange(match.rangeatindex(2)).string let userid = attrstring.attributedsubstringfromrange(match.rangeatindex(3)).string //a basic idea add link attribute on regex match range attrstring.addattribute(nslinkattributename, value: "\(userid)", range: match.rangeatindex(1)) //still text it's in format @(steve|user_id) how replace @steve keeping link attribute ? attrstring.replacecharactersinrange(match.rangeatindex(1), withstring: "@\(username)") } return attrstring }
Comments
Post a Comment