---
title: NSRegularExpression
framework: foundation
role: symbol
role_heading: Class
path: foundation/nsregularexpression
---

# NSRegularExpression

An immutable representation of a compiled regular expression that you apply to Unicode strings.

## Declaration

```swift
class NSRegularExpression
```

## Overview

Overview The fundamental matching method for NSRegularExpression is a Block iterator method that allows clients to supply a Block object which will be invoked each time the regular expression matches a portion of the target string.  There are additional convenience methods for returning all the matches as an array, the total number of matches, the first match, and the range of the first match. An individual match is represented by an instance of the NSTextCheckingResult class, which carries information about the overall matched range (via its range property), and the range of each individual capture group (via the range(at:) method).  For basic NSRegularExpression objects, these match results will be of type regularExpression, but subclasses may use other types. note: NSRegularExpression conforms to the International Components for Unicode (ICU) specification for regular expressions. Examples Using NSRegularExpression What follows are a set of graduated examples for using the NSRegularExpression class. All these examples use the regular expression \\b(a|b)(c|d)\\b as their regular expression. This snippet creates a regular expression to match two-letter words, in which the first letter is “a” or “b” and the second letter is “c” or “d”. Specifying caseInsensitive means that matches will be case-insensitive, so this will match “BC”, “aD”, and so forth, as well as their lower-case equivalents. The numberOfMatches(in:options:range:) method provides a simple mechanism for counting the number of matches in a given range of a string. If you are interested only in the overall range of the first match, the rangeOfFirstMatch(in:options:range:) method provides it for you.  Some regular expressions (though not the example pattern) can successfully match a zero-length range, so the comparison of the resulting range with {NSNotFound, 0} is the most reliable way to determine whether there was a match or not. The example regular expression contains two capture groups, corresponding to the two sets of parentheses, one for the first letter, and one for the second.  If you are interested in more than just the overall matched range, you want to obtain an NSTextCheckingResult object corresponding to a given match.  This object provides information about the overall matched range, via its range property, and also supplies the capture group ranges, via the range(at:) method.  The first capture group range is given by [result rangeAtIndex:1], the second by [result rangeAtIndex:2].  Sending a result the  range(at:) message and passing 0 is equivalent to [result range]. If the result returned is non-nil, then [result range] will always be a valid range, so it is not necessary to compare it against {NSNotFound, 0}.  However, for some regular expressions (though not the example pattern) some capture groups may or may not participate in a given match.  If a given capture group does not participate in a given match, then [result rangeAtIndex:idx] will return {NSNotFound, 0}. The matches(in:options:range:) returns all the matching results. The firstMatch(in:options:range:) method is similar to matches(in:options:range:) but it returns only the first match. The Block enumeration method enumerateMatches(in:options:range:using:) is the most general and flexible of the matching methods of NSRegularExpression.  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 example case, the iteration is stopped after a certain number of matches have been found. If neither of the special options reportProgress or reportCompletion is specified, then the result argument to the Block is guaranteed to be non-nil, and as mentioned before, it is guaranteed to have a valid overall range.  See NSRegularExpression.MatchingOptions for the significance of reportProgress or reportCompletion. NSRegularExpression also provides simple methods for performing find-and-replace operations on a string.  The following example returns a modified copy, but there is a corresponding method for modifying a mutable string in place.  The template specifies what is to be used to replace each match, with $0 representing the contents of the overall matched range, $1 representing the contents of the first capture group, and so on.  In this case, the template reverses the two letters of the word. Concurrency and Thread Safety NSRegularExpression is designed to be immutable and thread safe, so that a single instance can be used in matching operations on multiple threads at once.  However, the string on which it is operating should not be mutated during the course of a matching operation, whether from another thread or from within the Block used in the iteration. Regular Expression Syntax The following tables describe the character expressions used by the regular expression to match patterns within a string, the pattern operators that specify how many times a pattern is matched and additional matching restrictions, and the last table specifies flags that can be included in the regular expression pattern that specify search behavior over multiple lines (these flags can also be specified using the NSRegularExpression.Options option flags. Regular Expression Metacharacters Table 1: Character sequences used to match characters within a string.  |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |  Regular Expression Operators Table 2: Regular expression operators.  |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |  Template Matching Format The NSRegularExpression class provides find-and-replace methods for both immutable and mutable strings using the technique of template matching. Table 3: Find-and-replace syntax.  |   |   |  The replacement string is treated as a template, with $0 being replaced by the contents of the matched range, $1 by the contents of the first capture group, and so on.  Additional digits beyond the maximum required to represent the number of capture groups will be treated as ordinary characters, as will a $ not followed by digits.  Backslash will escape both $ and \. Flag Options The following flags control various aspects of regular expression matching. These flag values may be specified within the pattern using the (?ismx-ismx) pattern options.  Equivalent behaviors can be specified for the entire pattern when an NSRegularExpression is initialized, using the NSRegularExpression.Options option flags. Table 4: Regular expression matching flags.  |   |   |   |   |   |  Performance NSRegularExpression implements a nondeterministic finite automaton matching engine. As such, complex regular expression patterns containing multiple * or + operators may result in poor performance when attempting to perform matches — particularly failing to match a given input. For more information, see the “Performance Tips” section of the ICU User Guide. ICU License Tables 1, 2, 3, and 4 are reproduced from the ICU User Guide, Copyright (c) 2000 - 2009 IBM and Others, which are licensed under the following terms: COPYRIGHT AND PERMISSION NOTICE Copyright (c) 1995-2009 International Business Machines Corporation and others. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, provided that the above copyright notice(s) and this permission notice appear in all copies of the Software and that both the above copyright notice(s) and this permission notice appear in supporting documentation. THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. Except as contained in this notice, the name of a copyright holder shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization of the copyright holder. All trademarks and registered trademarks mentioned herein are the property of their respective owners.

## Topics

### Creating Regular Expressions

- [init(pattern:options:)](foundation/nsregularexpression/init(pattern:options:).md)

### Getting the Regular Expression and Options

- [pattern](foundation/nsregularexpression/pattern.md)
- [options](foundation/nsregularexpression/options-swift.property.md)
- [numberOfCaptureGroups](foundation/nsregularexpression/numberofcapturegroups.md)

### Searching Strings Using Regular Expressions

- [numberOfMatches(in:options:range:)](foundation/nsregularexpression/numberofmatches(in:options:range:).md)
- [enumerateMatches(in:options:range:using:)](foundation/nsregularexpression/enumeratematches(in:options:range:using:).md)
- [matches(in:options:range:)](foundation/nsregularexpression/matches(in:options:range:).md)
- [firstMatch(in:options:range:)](foundation/nsregularexpression/firstmatch(in:options:range:).md)
- [rangeOfFirstMatch(in:options:range:)](foundation/nsregularexpression/rangeoffirstmatch(in:options:range:).md)

### Replacing Strings Using Regular Expressions

- [replaceMatches(in:options:range:withTemplate:)](foundation/nsregularexpression/replacematches(in:options:range:withtemplate:).md)
- [stringByReplacingMatches(in:options:range:withTemplate:)](foundation/nsregularexpression/stringbyreplacingmatches(in:options:range:withtemplate:).md)

### Escaping Characters in a String

- [escapedTemplate(for:)](foundation/nsregularexpression/escapedtemplate(for:).md)
- [escapedPattern(for:)](foundation/nsregularexpression/escapedpattern(for:).md)

### Custom Replace Functionality

- [replacementString(for:in:offset:template:)](foundation/nsregularexpression/replacementstring(for:in:offset:template:).md)

### Constants

- [NSRegularExpression.Options](foundation/nsregularexpression/options-swift.struct.md)
- [NSRegularExpression.MatchingFlags](foundation/nsregularexpression/matchingflags.md)
- [NSRegularExpression.MatchingOptions](foundation/nsregularexpression/matchingoptions.md)

### Initializers

- [init(coder:)](foundation/nsregularexpression/init(coder:).md)

## Relationships

### Inherits From

- [NSObject](objectivec/nsobject-swift.class.md)

### Inherited By

- [NSDataDetector](foundation/nsdatadetector.md)

### Conforms To

- [CVarArg](swift/cvararg.md)
- [CustomDebugStringConvertible](swift/customdebugstringconvertible.md)
- [CustomStringConvertible](swift/customstringconvertible.md)
- [Equatable](swift/equatable.md)
- [Hashable](swift/hashable.md)
- [NSCoding](foundation/nscoding.md)
- [NSCopying](foundation/nscopying.md)
- [NSObjectProtocol](objectivec/nsobjectprotocol.md)
- [NSSecureCoding](foundation/nssecurecoding.md)
- [Sendable](swift/sendable.md)
- [SendableMetatype](swift/sendablemetatype.md)

## See Also

### Pattern Matching

- [Scanner](foundation/scanner.md)
- [NSDataDetector](foundation/nsdatadetector.md)
- [NSTextCheckingResult](foundation/nstextcheckingresult.md)
- [NSNotFound](foundation/nsnotfound-4qp9h.md)
