<!--
{
  "availability" : [
    "iOS: 4.0.0 -",
    "iPadOS: 4.0.0 -",
    "macCatalyst: 13.1.0 -",
    "macOS: 10.7.0 -",
    "tvOS: 9.0.0 -",
    "visionOS: 1.0.0 -",
    "watchOS: 2.0.0 -"
  ],
  "documentType" : "symbol",
  "framework" : "Foundation",
  "identifier" : "/documentation/Foundation/NSDataDetector",
  "metadataVersion" : "0.1.0",
  "role" : "Class",
  "symbol" : {
    "kind" : "Class",
    "modules" : [
      "Foundation"
    ],
    "preciseIdentifier" : "c:objc(cs)NSDataDetector"
  },
  "title" : "NSDataDetector"
}
-->

# NSDataDetector

A specialized regular expression object that matches natural language text for predefined data patterns.

```
class NSDataDetector
```

## Overview

Find dates, addresses, links, phone numbers, and transit information in natural language text with `NSDataDetector`.

`NSDataDetector` returns the results of matching content in [`NSTextCheckingResult`](/documentation/Foundation/NSTextCheckingResult) objects. The [`NSTextCheckingResult`](/documentation/Foundation/NSTextCheckingResult) objects that `NSDataDetector` returns are different from those that [`NSRegularExpression`](/documentation/Foundation/NSRegularExpression) returns. The results are one of the data detector’s types and contain the corresponding properties. For example, results of type [`date`](/documentation/Foundation/NSTextCheckingResult/CheckingType/date) have a [`date`](/documentation/Foundation/NSTextCheckingResult/date), [`timeZone`](/documentation/Foundation/NSTextCheckingResult/timeZone), and [`duration`](/documentation/Foundation/NSTextCheckingResult/duration); and results of type [`link`](/documentation/Foundation/NSTextCheckingResult/CheckingType/link) have a [`url`](/documentation/Foundation/NSTextCheckingResult/url).

> Important:
> Don’t use `NSDataDetector` to validate data. `NSDataDetector` discards potential matches in case of uncertainty. Use a class specific to the type of data for validation instead. For example, attempt to instantiate a ``doc://com.apple.foundation/documentation/Foundation/URL`` object using ``doc://com.apple.foundation/documentation/Foundation/URL/init(string:)`` to validate a URL string. A valid URL string returns an instance of ``doc://com.apple.foundation/documentation/Foundation/URL``, while an invalid URL string returns <doc://com.apple.documentation/documentation/ObjectiveC/nil-227m0>.

### Examples

The following shows several graduated examples of using the `NSDataDetector` class.

This code fragment creates a data detector that finds URL links and phone numbers. If an error occurs, it returns in `error`.

```objc
   NSError *error = nil;
   NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink|NSTextCheckingTypePhoneNumber
                                                              error:&error];
```

After creating the data detector instance, you can determine the number of matches within a range of a string using the `NSRegularExpression` method [`numberOfMatches(in:options:range:)`](/documentation/Foundation/NSRegularExpression/numberOfMatches(in:options:range:)).

```objc
   NSUInteger numberOfMatches = [detector numberOfMatchesInString:string
                                                          options:0
                                                            range:NSMakeRange(0, [string length])];
```

If you’re interested only in the overall range of the first match, the [`numberOfMatches(in:options:range:)`](/documentation/Foundation/NSRegularExpression/numberOfMatches(in:options:range:)) method provides it.  However, with data detectors, this is less likely than with regular expressions because clients are usually interested in additional information as well.

The additional information available depends on the type of the result.  For results of type [`link`](/documentation/Foundation/NSTextCheckingResult/CheckingType/link), it’s the `URL` property that’s significant.  For results of type `NSTextCheckingTypePhoneNumber` , it’s the `phoneNumber` property instead.

The [`matches(in:options:range:)`](/documentation/Foundation/NSRegularExpression/matches(in:options:range:)) method is similar to [`firstMatch(in:options:range:)`](/documentation/Foundation/NSRegularExpression/firstMatch(in:options:range:)), 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:

```objc
   NSArray *matches = [detector matchesInString:string
                                        options:0
                                          range:NSMakeRange(0, [string length])];
   for (NSTextCheckingResult *match in matches) {
        NSRange matchRange = [match range];
        if ([match resultType] == NSTextCheckingTypeLink) {
            NSURL *url = [match URL];
        } else if ([match resultType] == NSTextCheckingTypePhoneNumber) {
            NSString *phoneNumber = [match phoneNumber];
        }
   }
```

The `NSRegularExpression` 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 stops after finding a certain number of matches:

```objc
   __block NSUInteger count = 0;
   [detector enumerateMatchesInString:string
                              options:0
                                range:NSMakeRange(0, [string length])
                           usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop){
        NSRange matchRange = [match range];
        if ([match resultType] == NSTextCheckingTypeLink) {
            NSURL *url = [match URL];
        } else if ([match resultType] == NSTextCheckingTypePhoneNumber) {
            NSString *phoneNumber = [match phoneNumber];
        }
        if (++count >= 100) *stop = YES;
   }];
```

> Note:
> Only use `NSDataDetector` on natural language text.
> 
> If you expect text to be in a particular format, use an ``doc://com.apple.foundation/documentation/Foundation/Formatter`` or ``doc://com.apple.foundation/documentation/Foundation/ValueTransformer`` subclass instead. For instance, if you’re expecting a date field to be an ISO 8601 timestamp, use ``doc://com.apple.foundation/documentation/Foundation/DateFormatter`` to parse that into an ``doc://com.apple.foundation/documentation/Foundation/NSDate`` object.
> 
> If the text is in a machine-readable format, such as XML or JSON, extract the natural language text, such as by using ``doc://com.apple.foundation/documentation/Foundation/XMLParser`` or ``doc://com.apple.foundation/documentation/Foundation/JSONSerialization``, and match on that rather than attempt to match on the entire document.

## Topics

### Creating data detector instances

[`dataDetectorWithTypes:error:`](/documentation/Foundation/NSDataDetector/dataDetectorWithTypes:error:)

Creates and returns a new data detector instance.

[`init(types:)`](/documentation/Foundation/NSDataDetector/init(types:))

Initializes and returns a data detector instance.

### Getting the checking types

[`checkingTypes`](/documentation/Foundation/NSDataDetector/checkingTypes)

Returns the checking types for the data detector.



---

Copyright &copy; 2026 Apple Inc. All rights reserved. | [Terms of Use](https://www.apple.com/legal/internet-services/terms/site.html) | [Privacy Policy](https://www.apple.com/privacy/privacy-policy)