I have a certain string given like so..
let string = "[#he man:user:123] [#super man:user:456] [#bat man:user:789]"
Now, I need an array containing just the name and the id. For that, I applied the following regex..
extension String {
func findMentionText2() -> [[String]] {
let regex = try? NSRegularExpression(pattern: "(#\\w+(?: \\w+)*):user:(\\w+)", options: [])
if let matches = regex?.matches(in: self, options:[], range:NSMakeRange(0, self.count)) {
return matches.map { match in
return (1..<match.numberOfRanges).map {
let rangeBounds = match.range(at: $0)
guard let range = Range(rangeBounds, in: self) else {
return ""
}
return String(self[range])
}
}
} else {
return []
}
}
}
Now when I do let hashString = string.findMentionText() and print hashString, I get an array like so..
[["#he man", "123"], ["#super man", "456"], ["#bat man", "789"]]
So far so good..:)
Now I made a typealias and want to add it to an array..
So I did this...
typealias UserTag = (name: String, id: String)
var userTagList = [UserTag]()
and then,
let hashString2 = string.findMentionText2()
for unit in hashString2 {
let user: UserTag = (name: unit.first!, id: unit.last!)
userTagList.append(user)
}
for value in userTagList {
print(value.id)
print(value.name)
}
Now here, instead of giving unit.first and unit.last in let user: UserTag = (name: unit.first!, id: unit.last!), want to add the name and id to the typealias as and when they are matched from the regex..ie.when I get the name or id, it should be added to the array instead of giving unit.first or unit.last..
How can I achieve that..?
You just need to refactor your map to generate an array of UserTag instead of an array of string arrays. Here's one approach:
typealias UserTag = (name: String, id: String)
extension String {
func findMentionText2() -> [UserTag] {
let regex = try? NSRegularExpression(pattern: "(#\\w+(?: \\w+)*):user:(\\w+)", options: [])
if let matches = regex?.matches(in: self, options:[], range:NSMakeRange(0, self.count)) {
return matches.compactMap { match in
if match.numberOfRanges == 3 {
let name = String(self[Range(match.range(at: 1), in:self)!])
let id = String(self[Range(match.range(at: 2), in:self)!])
return UserTag(name: name, id: id)
} else {
return nil
}
}
} else {
return []
}
}
}
let string = "[#he man:user:123] [#super man:user:456] [#bat man:user:789]"
print(string.findMentionText2())
But I suggest you create a struct instead of using a tuple. It doesn't really change the implementation of findMentionText2 but using a struct lets you add other properties and methods as needed.
Related
I want to slice a very long string from one word to another. I want to get the substring between those words.
For that, I use the following string extension:
extension String {
func slice(from: String, to: String) -> String? {
guard let rangeFrom = range(of: from)?.upperBound else { return nil }
guard let rangeTo = self[rangeFrom...].range(of: to)?.lowerBound else { return nil }
return String(self[rangeFrom..<rangeTo])
}
That works really good, but my raw-string contains a few of the "from" "to"-words and I need every substring that is between of these two words, but with my extension I can ony get the first substring.
Example:
let raw = "id:244476end36475677id:383848448end334566777788id:55678900end543"
I want to get the following substrings from this raw string example:
sub1 = "244476"
sub2 = "383848448"
sub3 = "55678900"
If I call:
var text = raw.slice(from: "id:" , to: "end")
I only get the first occurence (text = "244476")
Thank you for reading. Every answer would be nice.
PS: I get always an error by making code snippets in stackoverflow.
You can get the ranges of your substrings using a while loop to repeat the search from that point to the end of your string and use map to get the substrings from the resulting ranges:
extension StringProtocol {
func ranges<S:StringProtocol,T:StringProtocol>(between start: S, and end: T, options: String.CompareOptions = []) -> [Range<Index>] {
var ranges: [Range<Index>] = []
var startIndex = self.startIndex
while startIndex < endIndex,
let lower = self[startIndex...].range(of: start, options: options)?.upperBound,
let range = self[lower...].range(of: end, options: options) {
let upper = range.lowerBound
ranges.append(lower..<upper)
startIndex = range.upperBound
}
return ranges
}
func substrings<S:StringProtocol,T:StringProtocol>(between start: S, and end: T, options: String.CompareOptions = []) -> [SubSequence] {
ranges(between: start, and: end, options: options).map{self[$0]}
}
}
Playground testing:
let string = """
your text
id:244476end
id:383848448end
id:55678900end
the end
"""
let substrings = string.substrings(between: "id:", and: "end") // ["244476", "383848448", "55678900"]
Rather thant trying to parse the string from start to end, I would use a combination of existing methods to transform it into the desire result. Here's How I would do this:
import Foundation
let raw = "id:244476end36475677id:383848448end334566777788id:55678900end543"
let result = raw
.components(separatedBy: "id:")
.filter{ !$0.isEmpty }
.map { segment -> String in
let slices = segment.components(separatedBy: "end")
return slices.first! // Removes the `end` and everything thereafter
}
print(result) // => ["244476", "383848448", "55678900"]
I am trying to get some data back from Core Spotlight which I am storing using a custom attribute key. Tested this on macOS and iOS as well, the result is always the same.
My test class:
import CoreSpotlight
class SpotlightSearch {
let domainId = "com.company.some"
let originalDataKeyName: String
init() {
self.originalDataKeyName = domainId.replacingOccurrences(of: ".", with: "_") + "_originalData"
}
func addToIndex(title: String, content: String) {
guard let originalDataKey = CSCustomAttributeKey(keyName: originalDataKeyName, searchable: false, searchableByDefault: false, unique: false, multiValued: false)
else { return }
let uniqueId = "MyUniqueId" + title
let originalContent = NSString(string: content)
let attributeSet = CSSearchableItemAttributeSet(itemContentType: kUTTypeText as String)
attributeSet.title = title
attributeSet.setValue(originalContent, forCustomKey: originalDataKey)
let item = CSSearchableItem(uniqueIdentifier: uniqueId, domainIdentifier: domainId, attributeSet: attributeSet)
CSSearchableIndex.default().indexSearchableItems([item]) { error in
if let error = error {
print("Indexing error: \(error.localizedDescription)")
} else {
print("Item '\(title)' successfully indexed!")
}
}
}
var query: CSSearchQuery?
func search(title: String) {
var allItems = [CSSearchableItem]()
let queryString = "title == '\(title)'cd"
let attributes = [ "title", originalDataKeyName ]
let newQuery = CSSearchQuery(queryString: queryString, attributes: attributes)
newQuery.foundItemsHandler = { (items: [CSSearchableItem]) -> Void in
allItems.append(contentsOf: items)
}
newQuery.completionHandler = { [weak self] (error: Error?) -> Void in
guard let originalDataKeyName = self?.originalDataKeyName,
let originalDataKey = CSCustomAttributeKey(keyName: originalDataKeyName)
else { return }
print("Search complete")
for item in allItems {
let attributeSet = item.attributeSet
let customData = attributeSet.value(forCustomKey: originalDataKey)
// Always nil
if customData == nil {
print("\(String(describing: originalDataKeyName)) not found in \(attributeSet.description)")
} else if let originalData = customData as? NSData {
let data = Data(referencing: originalData)
if let originalString = String(data: data, encoding: .utf8) {
print("Found '\(originalString)'")
}
}
}
}
query = newQuery
newQuery.start()
}
}
On app init:
let newSpotlightSearch = SpotlightSearch()
newSpotlightSearch.addToIndex(title: "Banana", content: "🍌")
Later:
spotlightSearch.search(title: "Banana")
It will find the title, but will not give me back the custom attribute value. If I put a breakpoint after "// Always nil" and use po attributeSet I will get
(lldb) po attributeSet
{
"_kMDItemBundleID" = "de.axelspringer.SearchMac";
"_kMDItemDomainIdentifier" = "com.company.some";
"_kMDItemExpirationDate" = "2018-08-26 00:00:00 +0000";
"_kMDItemExternalID" = MyUniqueIdBanana;
"com_company_some_originalData" = "\Ud83c\Udf4c";
kMDItemTitle = Banana;
}
So the value is there, but Spotlight will not return it to me. Already tried to use NSData instead of NSString for the custom attribute, but same result.
Also found this orphaned question in the Apple developer forums:
CSCustomAttributeKey valueForCustomKey not working
I believe it's iOS issue.
While it's not fixed, maybe Apple will allow you to use a private API to do your thing.
So, attributeSet has private Dictionaries attributes and customAttributes. You can try to get those values using Key Value Coding and ObjC:
NSDictionary *attributes = [attributeSet valueForKey:#"attributes"];
id customData = attributes[originalDataKeyName];
OR
NSDictionary *customAttributes = [attributeSet valueForKey:#"customAttributes"];
id customData = customAttributes[originalDataKeyName];
Key type in those dictionaries is either NSString* or CSCustomAttributeKey*, so you can try supplying both originalDataKeyName and originalDataKey.
I need to map the doors of buildings into a single map, from which afterward I need to populate three pickers using this data.
Each door contains the following data: building, level, range, door number and other information that is less relevant. So I created the following map:
public var doorsMap: [String : [String : [String : [String: Door]]]] = [:]
and a have a list of doors that I need to populate this map with, the problem is that I can't understand what should be the right syntax to perform this task, I tried:
doorsMap[door.building]?[door.level]?[door.range]?[door.number] = door
but this doesn't create the inner sets of dictionaries. when I tried to do:
doorsMap[door.building]![door.level]![door.range]![door.number] = door
Obviously, I get the:
Fatal error: Unexpectedly found nil while unwrapping an Optional value
because I try to unwrap a nil value.
So what would be the correct syntax in swift to populate this map from a list of doors?
A single assignment won't create the multiple, intermediate directories. You need to do it explicitly.
You could use something like this:
func add(door: Door) {
var building = self.doorsMap[door.building] ?? [String : [String:[String: Door]]]()
var level = building[door.level] ?? [String : [String: Door]]()
var range = level[door.range] ?? [String:Door]
range[door.number] = door
level[door.range] = range
building[door.level] = level
self.doorsMap[door.building] = building
}
Personally, I would look for a better data structure, perhaps use a struct to hold the doorsMap. This struct could have functions to handle the insertion and retrieval of doors.
Perhaps something like this:
struct Door {
let building: String
let level: String
let range: String
let number: String
}
struct DoorMap {
private var buildingsSet = Set<String>()
private var levelsSet = Set<String>()
private var rangesSet = Set<String>()
private var numberSet = Set<String>()
private var doorsArray = [Door]()
var buildings: [String] {
get {
return Array(buildingsSet).sorted()
}
}
var levels: [String] {
get {
return Array(levelsSet).sorted()
}
}
var ranges: [String] {
get {
return Array(rangesSet).sorted()
}
}
var numbers: [String] {
get {
return Array(numberSet).sorted()
}
}
var doors: [Door] {
get {
return doorsArray
}
}
mutating func add(door: Door) {
buildingsSet.insert(door.building)
levelsSet.insert(door.level)
rangesSet.insert(door.range)
numberSet.insert(door.number)
doorsArray.append(door)
}
func doorsMatching(building: String? = nil, level: String? = nil, range: String? = nil, number: String? = nil) -> [Door]{
let matches = doorsArray.filter { (potentialDoor) -> Bool in
var included = true
if let b = building {
if potentialDoor.building != b {
included = false
}
}
if let l = level {
if potentialDoor.level != l {
included = false
}
}
if let r = range {
if potentialDoor.range != r {
included = false
}
}
if let n = number {
if potentialDoor.number != n {
included = false
}
}
return included
}
return matches
}
}
var map = DoorMap()
let d1 = Door(building: "b1", level: "1", range: "r1", number: "1")
let d2 = Door(building: "b1", level: "2", range: "r1", number: "2")
let d3 = Door(building: "b2", level: "2", range: "r1", number: "2")
map.add(door: d1)
map.add(door: d2)
map.add(door: d3)
let b1Doors = map.doorsMatching(building:"b1")
let level2Doors = map.doorsMatching(level:"2")
let allBuildings = map.buildings()
Now, maybe you have more information on buildings and levels etc, so they could be structs too instead of just strings.
I have a String Add "ABC" here and I want to extract ABC from those string. For this I do:
text.rangeOfString("(?<=\")[^\"]+", options: .RegularExpressionSearch)
but it returns me
Optional(Range(5..<7))
How can I extract those text from there?
You firstly need to unwrap the resulted range, and call substringWithRange. You can do this via conditional binding
let text = "Add \"ABC\""
let range = text.rangeOfString("(?<=\")[^\"]+", options: .RegularExpressionSearch, range: nil, locale: nil)
if let nonNilRange = range {
print(text.substringWithRange(nonNilRange))
}
You can use the "([^"]+)" regex to extract any matches and any captured groups with the following code:
func regMatchGroup(regex: String, text: String) -> [[String]] {
do {
var resultsFinal = [[String]]()
let regex = try NSRegularExpression(pattern: regex, options: [])
let nsString = text as NSString
let results = regex.matchesInString(text,
options: [], range: NSMakeRange(0, nsString.length))
for result in results {
var internalString = [String]()
for var i = 0; i < result.numberOfRanges; ++i{
internalString.append(nsString.substringWithRange(result.rangeAtIndex(i)))
}
resultsFinal.append(internalString)
}
return resultsFinal
} catch let error as NSError {
print("invalid regex: \(error.localizedDescription)")
return [[]]
}
}
// USAGE:
let string = "Add \"ABC\" \"ABD\""
let matches = regMatchGroup("\"([^\"]+)\"", text: string)
if (matches.count > 0) // If we have matches....
{
print(matches[0][1]) // Print the first one, Group 1.
}
See SwiftStub demo
Due to error handling added, no crash should occur when no match is found.
The solution is:
let regex = myText.rangeOfString("(?<=\")[^\"]+")
myText.substringWithRange(regex, options: .RegularExpressionSearch)!)
If my main array is ["Hello","Bye","Halo"], and I'm searching for "lo", it will filter the array only to ["Hello", "Halo"].
This is what I've tried:
let matchingTerms = filter(catalogNames) {
$0.rangeOfString(self.txtField.text!, options: .CaseInsensitiveSearch) != nil
}
It throws
Type of expression is ambiguous without more context
Any suggestions?
Use contains instead:
let arr = ["Hello","Bye","Halo"]
let filtered = arr.filter { $0.contains("lo") }
print(filtered)
Output
["Hello", "Halo"]
Thanks to #user3441734 for pointing out that functionality is of course only available when you import Foundation
In Swift 3.0
let terms = ["Hello","Bye","Halo"]
var filterdTerms = [String]()
func filterContentForSearchText(searchText: String) {
filterdTerms = terms.filter { term in
return term.lowercased().contains(searchText.lowercased())
}
}
filterContentForSearchText(searchText: "Lo")
print(filterdTerms)
Output
["Hello", "Halo"]
Swift 3.1
let catalogNames = [ "Hats", "Coats", "Trousers" ]
let searchCatalogName = "Hats"
let filteredCatalogNames = catalogNames.filter { catalogName in
return catalogName.localizedCaseInsensitiveContains(searchCatalogName)
}
print(filteredCatalogNames)
my try...
let brands = ["Apple", "FB", "Google", "Microsoft", "Amazon"]
let b = brands.filter{(x) -> Bool in
(x.lowercased().range(of: "A".lowercased()) != nil)
}
print(b) //["Apple", "Amazon"]
with help of String extension you can use pure Swift solution (without import Foundation). I didn't check the speed, but it shouldn't be worse as the foundation equivalent.
extension String {
func contains(string: String)->Bool {
guard !self.isEmpty else {
return false
}
var s = self.characters.map{ $0 }
let c = string.characters.map{ $0 }
repeat {
if s.startsWith(c){
return true
} else {
s.removeFirst()
}
} while s.count > c.count - 1
return false
}
}
let arr = ["Hello","Bye","Halo"]
let filtered = arr.filter { $0.contains("lo") }
print(filtered) // ["Hello", "Halo"]
"a".contains("alphabet") // false
"alphabet".contains("") // true
You also need to compare to NSNotFound. The documentation for rangeOfString:options: says:
An NSRange structure giving the location and length in the receiver of the first occurrence of aString, modulo the options in mask. Returns {NSNotFound, 0} if aString is not found or is empty (#"").
import Foundation
let catalogNames = [ "Hats", "Coats", "Trousers" ]
let matchingTerms = catalogNames.filter {
$0.rangeOfString(self.txtField.text!, options: .CaseInsensitiveSearch).location != NSNotFound
}
Swift 5:
Considered below example. Filtering (case insensitive) out data from array 1 and populating 2nd array with that
let data = ["Apple", "Oranges", "Banana", "Grapes"]
var filteredData = [String]()
func filterText(_ text: String?) {
guard let text = text else {return}
filteredData.removeAll()
for element in data {
if element.lowercased().starts(with: text.lowercased()){
filteredData.append(element)
}
}
}