0

I want to specify my value in regular expression, how can I do it?

What I am doing:

request.predicate = Predicate(format: "entityProperty MATCHES [c] '[^0123]%@'", myValue)

Observing the result, I can say that %@ is parsed as a characters in the regex string, no value is placed instead of it

Here is some explanation on usage of regular expressions with predicates, but no information about placeholders for values

spin_eight
  • 3,925
  • 10
  • 39
  • 61

2 Answers2

1

Your Solution would work for:

  1. myValue is representing valid regex pattern.
  2. myValue may not contain single quotes (').

If myValue may contain single quote, this would work:

request.predicate = NSPredicate(format: "entityProperty MATCHES [c] %@", "[^1234]" + myValue)

And if myValue is not a regex pattern and may contain some meta-characters, you may need to write something like this:

request.predicate = NSPredicate(format: "entityProperty MATCHES [c] %@", "[^1234]"+NSRegularExpression.escapedPattern(for: myValue))

Anyway, you need to remember:

Single or double quoting variables (or substitution variable strings) cause %@, %K, or $variable to be interpreted as a literal in the format string and so prevent any substitution.

Parser Basics (Predicate Programming Guide)

(I used NSPredicate as Predicate is not available in Xcode 8 beta 6.)

OOPer
  • 47,149
  • 6
  • 107
  • 142
  • @OOPer, thank you. Do you know how I can combine statements like CONTAINS text0 AND CONTAINS text1 in predicate? – spin_eight Aug 27 '16 at 11:01
  • @spin_eight, `NSPredicate(format: "entityProperty CONTAINS %@ AND entityProperty CONTAINS %@", text0, text1)` would work. If I may be missing something, please give me a little more context. – OOPer Aug 27 '16 at 11:11
  • @OOPer My mistake, apologize me, i have read this [answer](http://stackoverflow.com/a/38723245/6433023) and get more idea about it. – Nirav D Aug 27 '16 at 12:04
  • @NDoc, I know I could mistake, so I should welcome all sorts of comments. Please do not hesitate to pointing my mistakes in the future. One thing I recommend to you that you'd better respect other sources than SO. Good luck for you and for your apps. – OOPer Aug 27 '16 at 12:16
0
request.predicate = Predicate(format: "entityProperty MATCHES [c] '[^0123]\(myValue)'")

Solution:
instead of %@ placeholder use string substitution: "prefixSomeText\(myValue)suffixSomeText"

Nirav D
  • 71,513
  • 12
  • 161
  • 183
spin_eight
  • 3,925
  • 10
  • 39
  • 61