Skip to content

Instantly share code, notes, and snippets.

@iSapozhnik
Last active November 13, 2018 17:03
Show Gist options
  • Save iSapozhnik/1f4698fc1dc0457bbae7ed48351d49fe to your computer and use it in GitHub Desktop.
Save iSapozhnik/1f4698fc1dc0457bbae7ed48351d49fe to your computer and use it in GitHub Desktop.
Substring of a string without taking into account of some characters
import Foundation
extension NSRange {
static func rangeOf(text: String, contains searchKey: String, with filterCharacters: [Character]?) -> NSRange {
var filter = "[ ]{0,1}("
filterCharacters?.forEach { filterCharacter in
filter += "\\" + String(filterCharacter)
if let lastCharacter = filterCharacters?.last, lastCharacter != filterCharacter {
filter += "|"
}
}
filter += "){0,1}[ ]{0,1}"
var regex = ""
searchKey.forEach { character in
regex += "[" + String(character) + "]{1}"
if let lastCharacter = searchKey.last, character != lastCharacter {
regex += filter
}
}
print(regex)
return (text as NSString).range(of: regex, options: .regularExpression, range: NSRange(location: 0, length: text.length), locale: nil)
}
}
let string = "MDX6"
let plate = "AM / DX6044"
let filter: [Character] = ["-", "/"]
let range = NSRange.rangeOf(text: plate, contains: string, with: filter)
print(range)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment