0

for exam:

I stored V«003» text in the core data id attribute.

If I pass the 003 or V003 to the NSPredicate it should approve the search, but because of « and » characters the NSFetchRequest couldn't find the field.

How could I ignore « and » characters in NSPredicate?

Is there any Regular Expression way for NSPredicate?

Vahid
  • 3,352
  • 2
  • 34
  • 42
  • 1
    You can find answer from this link. https://stackoverflow.com/questions/34320433/how-can-i-modify-nspredicate-to-ignore-whitespaces-in-swift – Khushbu May 09 '18 at 13:11
  • Remove the unwanted characters before searching. [Check out this question.](https://stackoverflow.com/q/32339717/3151675) – Tamás Sengel May 09 '18 at 13:12
  • @Khushbu, It's not the answer. because of `NSFetchedResultsController` I can't use 2 steps filtering. – Vahid May 12 '18 at 04:22
  • @the4kman, I have that bad characters in the stored data in coredata, I shouldn't change stored data because of my search. – Vahid May 12 '18 at 04:23

1 Answers1

1

It's pretty easy with Regular Expression, the question mark indicates an optional character.

let pattern = "V«?003»?"
NSPredicate(format: "id MATCHES %@", pattern)

Edit: to fix user input, I added «?»? between every user input characters:

func generatePattern(item: String) -> String {
    var str = ""
    for st in item {
        str.append(contentsOf: "«?»?")
        str.append(st)
    }
    str.append(contentsOf: "«?»?")
    return String(str)
}
Vahid
  • 3,352
  • 2
  • 34
  • 42
vadian
  • 274,689
  • 30
  • 353
  • 361
  • I just have `V003` characters that user entered and the `V` char is not static. It not possible to generate pattern! right? – Vahid May 12 '18 at 04:56
  • If the `V` is not static but `003` is then use `"\\w«?003»?"`. `\\w` is one arbitrary alphanumeric character. Or if you want to restrict it to uppercase letters use `"[A-Z]«?003»?"` – vadian May 12 '18 at 05:52
  • Because of bad backend design, I think it's better to put `«?»?` between every chars. BTW, thanks for your new solution. ;-) – Vahid May 12 '18 at 05:54