NSData class is a specialized subclass of
NSRegular designed to match natural language text for predefined data patterns.
- iOS 4.0+
- macOS 10.7+
- tvOS 9.0+
- watchOS 2.0+
NSData class can match dates, addresses, links, phone numbers and transit information.
The results of matching content is returned as
NSText objects. However, the
NSText objects returned by
NSData are different from those returned by the base class
NSRegular. Results returned by
NSData will be of one of the data detectors types, depending on the type of result being returned, and they will have corresponding properties. For example, results of type
date have a
duration; results of type
link have a
url, and so forth.
The following shows several graduated examples of using the
This code fragment creates a data detector that will find URL links and phone numbers. If an error was encountered it is returned in
Once the data detector instance is created you can determine the number of matches within a range of a string using the
If you are interested only in the overall range of the first match, the
number method provides it. However, with data detectors, this is less likely than with regular expressions, because clients usually will be interested in additional information as well.
The additional information available depends on the type of the result. For results of type
link, it is the
URL property that is significant. For results of type
NSText , it is the
phone property instead.
matches(in: method is similar to the
first, except that it returns all matches rather than only the first. The following code fragment finds all the matches for links and phone numbers in a string.
NSRegular block object enumerator is the most general and flexible of the matching methods. It allows you to iterate through matches in a string, performing arbitrary actions on each as specified by the code in the block, and to stop partway through if desired. In the following code fragment, the iteration is stopped after a certain number of matches have been found.