[Pitch] Predicate Regex Support

Hi all,

I would like to pitch new APIs for Predicate to add support for using Swift's regular expressions (via the Regex type) for complex pattern matching in strings. Please let me know if you have any questions/thoughts!

Predicate Regex Support

  • Proposal: SF-NNNN
  • Author(s): Jeremy Schonfeld
  • Review Manager: TBD
  • Status: Pitch
  • Implementation: coming soon

Introduction/Motivation

NSPredicate supports complex string pattern matching via regular expression support. For example, you could write an NSPredicate such as NSPredicate(format: "zipcode MATCHES %@", "\\d{5}(-\\d{4})?") in order to match records where the zipcode string property is a valid US postal code. The new swift Predicate type supports basic string matching using functions/operators such as ==, contains, localizedStandardContains, localizedCompare, and caseInsensitiveCompare, however Predicate does not currently support complex pattern matching operations such as regular expression matching.

Proposed solution and example

In order to help continue to achieve feature parity with NSPredicate and ease Predicate adoption for developers with complex matching logic, we'd like to add regex support to Predicate. We propose adding new APIs to allow developers to use the new swift-designed Regex type within Predicates. For example:

let regex = Regex {
	Anchor.startOfSubject
	Repeat(.digit, count: 5)
	Optionally {
		"-"
		Repeat(.digit, count: 4)
	}
	Anchor.endOfSubject
}

let predicate = #Predicate<Address> {
	$0.zipcode.contains(regex)
}

// - OR -

let predicate = #Predicate<Address> {
	$0.zipcode.contains(/^\d{5}(-\d{4})?$/)
}

I've posted the full pitch including the detailed design here on the swift-foundation repo. Check out the full pitch to read more info about the proposed design.

9 Likes