swift - Find backward in string first substring that belongs to a set (regex?) -
i have set of string set , find first occurrence of 1 string of set substring of string string. search in backward direction position (an integer).
i have written code uses loop able write in more compact way, maybe regex needed.
can please me?
edit. temporary solution: currentposition integer value given nstextview, command string manipulating, doing checking if character after 1 @ currentposition " " or if last of string command. in such cases extrapolate substring of command spaces currentposition nearest (in backward direction) delimiter (defined in code).
what in question called set here array of string , represented separators, string here command, , position here currentposition.
let currentposition = self.selectedrange().location let currentpositionindex = command.index(command.startindex,offsetby: currentposition) if(currentposition == command.characters.count || command[currentpositionindex] == " ") { let separatorsstring = " .,:~/!+=\\;/?" let separators = separatorsstring.characters //todo: use regex in order clean code var nearestseparatorposition = command.startindex outerloop: in stride(from: currentposition - 1, to: -1, by: -1) { separator in separators { let index = command.index(command.startindex, offsetby: i) if(command[index] == separator) { nearestseparatorposition = command.index(index, offsetby: 1) break outerloop } } } swift.print("current word index = (\(command.distance(from: command.startindex, to: nearestseparatorposition)),\(command.distance(from: command.startindex, to: currentpositionindex)))") let currentword = command.substring(with: nearestseparatorposition ..< currentpositionindex)
i'm not sure if have things flipped around, based un understanding of question do:
func findfirstcontaining(needle item: string, in haystack: [string]) -> string? { let stringranges: [range<string.index>] = haystack.flatmap { return item.range(of: $0) } .sorted { $0.lowerbound < $1.lowerbound } if let range = stringranges.first { return item.substring(with: range) } else { return nil } } let testset: set<string> = ["test", "string", "set"] let needle = "this test" // evaluates "test" let result = findfirstcontaining(needle: needle, in: testset.sorted()) let reversedresult = findfirstcontaining(needle: needle, in: testset.sorted().reversed()) this inefficient, i'm not sure problem you're trying solve.
Comments
Post a Comment