iOS中NSRegularExpression使用
NSRegularExpression的使用
1.生成
+ (NSRegularExpression *)regularExpressionWithPattern:(NSString *)pattern options:(NSRegularExpressionOptions)options error:(NSError **)error;
pattern即是正则表达式的模式字符串
+ (NSString *)escapedPatternForString:(NSString *)string
该函数用来将模式字符串中的特殊字符通过添加“\”进行处理
如@“$abc”->@"\\$abc"因为“\”本身需要转义,所以是两个反斜杆。
1 NSError *error = nil; 2 NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^ac" options:NSRegularExpressionCaseInsensitive error:&error]; 3 NSString *string = @"acbcadf^f"; 4 string = [NSRegularExpression escapedPatternForString:string]; 5 NSUInteger numberOfMatches = [regex numberOfMatchesInString:string options:0 range:NSMakeRange(0, string.length)];\\numberOfMatches == 1
The NSRegularExpression class is used to represent and apply regular expressions to Unicode strings. An instance of this class is an immutable representation of a compiled regular expression pattern and various option flags. The pattern syntax currently supported is that specified by ICU. The ICU regular expressions are described at http://userguide.icu-project.org/strings/regexp.
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 rangeAtIndex: method). For basic NSRegularExpression objects, these match results will be of type NSTextCheckingTypeRegularExpression, but subclasses may use other types.
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 NSRegularExpressionCaseInsensitive means that matches will be case-insensitive, so this will match “BC”, “aD”, and so forth, as well as their lower-case equivalents.
NSError *error = NULL;NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\b(a|b)(c|d)\\b"options:NSRegularExpressionCaseInsensitiveerror:&error];
The numberOfMatchesInString:options:range: method provides a simple mechanism for counting the number of matches in a given range of a string.
NSUInteger numberOfMatches = [regex numberOfMatchesInString:stringoptions:0range:NSMakeRange(0, [string length])];
If you are interested only in the overall range of the first match, the rangeOfFirstMatchInString: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 rangeAtIndex: method. The first capture group range is given by [result rangeAtIndex:1], the second by [result rangeAtIndex:2]. Sending a result the rangeAtIndex: 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}.
NSRange rangeOfFirstMatch = [regex rangeOfFirstMatchInString:string options:0 range:NSMakeRange(0, [string length])];if (!NSEqualRanges(rangeOfFirstMatch, NSMakeRange(NSNotFound, 0))) {NSString *substringForFirstMatch = [string substringWithRange:rangeOfFirstMatch];}
The matchesInString:options:range: returns all the matching results.
NSArray *matches = [regex matchesInString:stringoptions:0range:NSMakeRange(0, [string length])];for (NSTextCheckingResult *match in matches) {NSRange matchRange = [match range];NSRange firstHalfRange = [match rangeAtIndex:1];NSRange secondHalfRange = [match rangeAtIndex:2];}
The firstMatchInString:options:range: method is similar to matchesInString:options:range: but it returns only the first match.
NSTextCheckingResult *match = [regex firstMatchInString:stringoptions:0range:NSMakeRange(0, [string length])];if (match) {NSRange matchRange = [match range];NSRange firstHalfRange = [match rangeAtIndex:1];NSRange secondHalfRange = [match rangeAtIndex:2];}}
The Block enumeration method enumerateMatchesInString:options:range:usingBlock: 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 NSMatchingReportProgress or NSMatchingReportCompletion 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 NSMatchingOptions for the significance of NSMatchingReportProgress or NSMatchingReportCompletion.
__block NSUInteger count = 0;[regex enumerateMatchesInString:string options:0 range:NSMakeRange(0, [string length]) usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop){NSRange matchRange = [match range];NSRange firstHalfRange = [match rangeAtIndex:1];NSRange secondHalfRange = [match rangeAtIndex:2];if (++count >= 100) *stop = YES;}];
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.
NSString *modifiedString = [regex stringByReplacingMatchesInString:stringoptions:0range:NSMakeRange(0, [string length])withTemplate:@"$2$1"];
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 NSRegularExpressionOptions option flags.
Regular Expression Metacharacters
Table 1 describe the character sequences used to match characters within a string.
|
Character Expression |
Description |
|---|---|
|
|
Match a BELL, |
|
|
Match at the beginning of the input. Differs from |
|
|
Match if the current position is a word boundary. Boundaries occur at the transitions between word ( |
|
|
Match a BACKSPACE, |
|
|
Match if the current position is not a word boundary. |
|
|
Match a |
|
|
Match any character with the Unicode General Category of Nd (Number, Decimal Digit.) |
|
|
Match any character that is not a decimal digit. |
|
|
Match an |
|
|
Terminates a |
|
|
Match a FORM FEED, |
|
|
Match if the current position is at the end of the previous match. |
|
|
Match a |
|
|
Match the named character. |
|
|
Match any character with the specified Unicode Property. |
|
|
Match any character not having the specified Unicode Property. |
|
|
Quotes all following characters until |
|
|
Match a CARRIAGE RETURN, \u000D. |
|
|
Match a white space character. White space is defined as [\t\n\f\r\p{Z}]. |
|
|
Match a non-white space character. |
|
|
Match a HORIZONTAL TABULATION, |
|
|
Match the character with the hex value hhhh. |
|
|
Match the character with the hex value hhhhhhhh. Exactly eight hex digits must be provided, even though the largest Unicode code point is |
|
|
Match a word character. Word characters are [\p{Ll}\p{Lu}\p{Lt}\p{Lo}\p{Nd}]. |
|
|
Match a non-word character. |
|
|
Match the character with hex value hhhh. From one to six hex digits may be supplied. |
|
|
Match the character with two digit hex value hh. |
|
|
Match a Grapheme Cluster. |
|
|
Match if the current position is at the end of input, but before the final line terminator, if one exists. |
|
|
Match if the current position is at the end of input. |
|
|
Back Reference. Match whatever the nth capturing group matched. n must be a number |
|
|
Match an Octal character. ooo is from one to three octal digits. |
|
|
Match any one character from the pattern. |
|
|
Match any character. See |
|
|
Match at the beginning of a line. See |
|
|
Match at the end of a line. See |
|
|
Quotes the following character. Characters that must be quoted to be treated as literals are |
Regular Expression Operators
Table 2 defines the regular expression operators.
|
Operator |
Description |
|---|---|
|
|
Alternation. A |
|
|
Match |
|
|
Match |
|
|
Match zero or one times. Prefer one. |
|
|
Match exactly n times. |
|
|
Match at least n times. Match as many times as possible. |
|
|
Match between n and m times. Match as many times as possible, but not more than m. |
|
|
Match |
|
|
Match 1 or more times. Match as few times as possible. |
|
|
Match zero or one times. Prefer zero. |
|
|
Match exactly n times. |
|
|
Match at least n times, but no more than required for an overall pattern match. |
|
|
Match between n and m times. Match as few times as possible, but not less than n. |
|
|
Match 0 or more times. Match as many times as possible when first encountered, do not retry with fewer even if overall match fails (Possessive Match). |
|
|
Match 1 or more times. Possessive match. |
|
|
Match zero or one times. Possessive match. |
|
|
Match exactly n times. |
|
|
Match at least n times. Possessive Match. |
|
|
Match between n and m times. Possessive Match. |
|
|
Capturing parentheses. Range of input that matched the parenthesized subexpression is available after the match. |
|
|
Non-capturing parentheses. Groups the included pattern, but does not provide capturing of matching text. Somewhat more efficient than capturing parentheses. |
|
|
Atomic-match parentheses. First match of the parenthesized subexpression is the only one tried; if it does not lead to an overall pattern match, back up the search for a match to a position before the " |
|
|
Free-format comment |
|
|
Look-ahead assertion. True if the parenthesized pattern matches at the current input position, but does not advance the input position. |
|
|
Negative look-ahead assertion. True if the parenthesized pattern does not match at the current input position. Does not advance the input position. |
|
(?<= ... ) |
Look-behind assertion. True if the parenthesized pattern matches text preceding the current input position, with the last character of the match being the input character just before the current position. Does not alter the input position. The length of possible strings matched by the look-behind pattern must not be unbounded (no * or + operators.) |
|
|
Negative Look-behind assertion. True if the parenthesized pattern does not match text preceding the current input position, with the last character of the match being the input character just before the current position. Does not alter the input position. The length of possible strings matched by the look-behind pattern must not be unbounded (no * or + operators.) |
|
|
Flag settings. Evaluate the parenthesized expression with the specified flags enabled or -disabled. The flags are defined in Flag Options. |
|
|
Flag settings. Change the flag settings. Changes apply to the portion of the pattern following the setting. For example, (?i) changes to a case insensitive match.The flags are defined in Flag Options. |
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 describes the syntax.
|
Character |
Descriptions |
|---|---|
|
|
The text of capture group n will be substituted for $n. n must be |
|
|
Treat the following character as a literal, suppressing any special meaning. Backslash escaping in substitution text is only required for '$' and '\', but may be used on any other character without bad effects. |
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 NSRegularExpressionOptions option flags.
|
Flag (Pattern) |
Description |
|---|---|
|
i |
If set, matching will take place in a case-insensitive manner. |
|
x |
If set, allow use of white space and #comments within patterns |
|
s |
If set, a " |
|
m |
Control the behavior of " |
|
Para |
Controls the behavior of |
ICU License
Table 1, Table 2, Table 3, Table 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.
-
Creates an NSRegularExpression instance with the specified regular expression pattern and options.
Declaration
SWIFT
class func regularExpressionWithPattern(_pattern: String,
optionsoptions: NSRegularExpressionOptions,
errorerror: NSErrorPointer) -> NSRegularExpression?OBJECTIVE-C
+ (NSRegularExpression *)regularExpressionWithPattern:(NSString *)patternoptions:(NSRegularExpressionOptions)optionserror:(NSError **)errorParameters
patternThe regular expression pattern to compile.
optionsThe matching options. See NSRegularExpressionOptions for possible values. The values can be combined using the C-bitwise
ORoperator.errorAn out value that returns any error encountered during initialization. Returns an
NSErrorobject if the regular expression pattern is invalid; otherwise returnsnil.Return Value
An instance of
NSRegularExpressionfor the specified regular expression and options.Import Statement
import FoundationAvailability
Available in iOS 4.0 and later.
See Also
-
Returns an initialized NSRegularExpression instance with the specified regular expression pattern and options.
Declaration
SWIFT
init(patternpattern: String,
optionsoptions: NSRegularExpressionOptions,
errorerror: NSErrorPointer)OBJECTIVE-C
- (instancetype)initWithPattern:(NSString *)patternoptions:(NSRegularExpressionOptions)optionserror:(NSError **)errorParameters
patternThe regular expression pattern to compile.
optionsThe regular expression options that are applied to the expression during matching. See NSRegularExpressionOptions for possible values.
errorAn out value that returns any error encountered during initialization. Returns an
NSErrorobject if the regular expression pattern is invalid; otherwise returnsnil.firstMatchInString:options:rangeReturn Value
An instance of
NSRegularExpressionfor the specified regular expression and options.Import Statement
import FoundationAvailability
Available in iOS 4.0 and later.
-
-
Returns the options used when the regular expression option was created. (read-only)
Declaration
SWIFT
var options: NSRegularExpressionOptions { get }OBJECTIVE-C
@property(readonly) NSRegularExpressionOptions optionsDiscussion
The options property specifies aspects of the regular expression matching that are always used when matching the regular expression. For example, if the expression is case sensitive, allows comments, ignores metacharacters, etc.. See NSRegularExpressionOptions for a complete discussion of the possible constants and their meanings.
Import Statement
import FoundationAvailability
Available in iOS 4.0 and later.
-
Returns the number of capture groups in the regular expression. (read-only)
Declaration
SWIFT
var numberOfCaptureGroups: Int { get }OBJECTIVE-C
@property(readonly) NSUInteger numberOfCaptureGroupsDiscussion
A capture group consists of each possible match within a regular expression. Each capture group can then be used in a replacement template to insert that value into a replacement string.
This value puts a limit on the values of
nfor$nin templates, and it determines the number of ranges in the returnedNSTextCheckingResultinstances returned in thematch...methods.An exception will be generated if you attempt to access a result with an index value exceeding
numberOfCaptureGroups-1.Import Statement
import FoundationAvailability
Available in iOS 4.0 and later.
-
-
Returns the number of matches of the regular expression within the specified range of the string.
Declaration
SWIFT
func numberOfMatchesInString(_string: String,
optionsoptions: NSMatchingOptions,
rangerange: NSRange) -> IntOBJECTIVE-C
- (NSUInteger)numberOfMatchesInString:(NSString *)stringoptions:(NSMatchingOptions)optionsrange:(NSRange)rangeParameters
stringThe string to search.
optionsThe matching options to use. See NSMatchingOptions for possible values.
rangeThe range of the string to search.
Return Value
The number of matches of the regular expression.
Discussion
This is a convenience method that calls
enumerateMatchesInString:options:range:usingBlock:.Import Statement
import FoundationAvailability
Available in iOS 4.0 and later.
-
Enumerates the string allowing the Block to handle each regular expression match.
Declaration
SWIFT
func enumerateMatchesInString(_string: String,
optionsoptions: NSMatchingOptions,
rangerange: NSRange,
usingBlockblock: (NSTextCheckingResult!,
NSMatchingFlags,
UnsafeMutablePointer<ObjCBool>) -> Void)OBJECTIVE-C
- (void)enumerateMatchesInString:(NSString *)stringoptions:(NSMatchingOptions)optionsrange:(NSRange)rangeusingBlock:(void (^)(NSTextCheckingResult *result,
NSMatchingFlags flags,
BOOL *stop))blockParameters
stringThe string.
optionsThe matching options to report. See NSMatchingOptions for the supported values.
rangeThe range of the string to test.
blockThe Block enumerates the matches of the regular expression in the string..
The block takes three arguments:
resultAn
NSTextCheckingResultspecifying the match. This result gives the overall matched range via itsrangeproperty, and the range of each individual capture group via itsrangeAtIndex:method. The range {NSNotFound, 0} is returned if one of the capture groups did not participate in this particular match.flagsThe current state of the matching progress. See NSMatchingFlags for the possible values.
stopA reference to a Boolean value. The Block can set the value to
YESto stop further processing of the array. The stop argument is an out-only argument. You should only ever set this Boolean toYESwithin the Block.The Block returns void.
Discussion
This method is the fundamental matching method for regular expressions and is suitable for overriding by subclassers. 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.
By default, the Block iterator method calls the Block precisely once for each match, with a non-
nilresultand the appropriateflags. The client may then stop the operation by setting the contents ofstoptoYES. Thestopargument is an out-only argument. You should only ever set this Boolean toYESwithin the Block.If the
NSMatchingReportProgressmatching option is specified, the Block will also be called periodically during long-running match operations, withnilresult andNSMatchingProgressmatching flag set in the Block’sflagsparameter, at which point the client may again stop the operation by setting the contents of stop toYES.If the
NSMatchingReportCompletionmatching option is specified, the Block object will be called once after matching is complete, withnilresult and theNSMatchingCompletedmatching flag is set in theflagspassed to the Block, plus any additional relevant NSMatchingFlags from amongNSMatchingHitEnd,NSMatchingRequiredEnd, orNSMatchingInternalError.NSMatchingProgressandNSMatchingCompletedmatching flags have no effect for methods other than this method.The
NSMatchingHitEndmatching flag is set in theflagspassed to the Block if the current match operation reached the end of the search range. TheNSMatchingRequiredEndmatching flag is set in theflagspassed to the Block if the current match depended on the location of the end of the search range.The NSMatchingFlags matching flag is set in the
flagspassed to the block if matching failed due to an internal error (such as an expression requiring exponential memory allocations) without examining the entire search range.The
NSMatchingAnchored,NSMatchingWithTransparentBounds, andNSMatchingWithoutAnchoringBoundsregular expression options, specified in theoptionsproperty specified when the regular expression instance is created, can apply to any match or replace method.If
NSMatchingAnchoredmatching option is specified, matches are limited to those at the start of the search range.If
NSMatchingWithTransparentBoundsmatching option is specified, matching may examine parts of the string beyond the bounds of the search range, for purposes such as word boundary detection, lookahead, etc.If
NSMatchingWithoutAnchoringBoundsmatching option is specified,^and$will not automatically match the beginning and end of the search range, but will still match the beginning and end of the entire string.NSMatchingWithTransparentBoundsandNSMatchingWithoutAnchoringBoundsmatching options have no effect if the search range covers the entire string.Import Statement
import FoundationAvailability
Available in iOS 4.0 and later.
-
Returns an array containing all the matches of the regular expression in the string.
Declaration
SWIFT
func matchesInString(_string: String,
optionsoptions: NSMatchingOptions,
rangerange: NSRange) -> [AnyObject]OBJECTIVE-C
- (NSArray *)matchesInString:(NSString *)stringoptions:(NSMatchingOptions)optionsrange:(NSRange)rangeParameters
stringThe string to search.
optionsThe matching options to use. See NSMatchingOptions for possible values.
rangeThe range of the string to search.
Return Value
An array of
NSTextCheckingResultobjects. Each result gives the overall matched range via itsrangeproperty, and the range of each individual capture group via itsrangeAtIndex:method. The range {NSNotFound, 0} is returned if one of the capture groups did not participate in this particular match.Discussion
This is a convenience method that calls
enumerateMatchesInString:options:range:usingBlock:passing the appropriate string, options, and range..Import Statement
import FoundationAvailability
Available in iOS 4.0 and later.
-
Returns the first match of the regular expression within the specified range of the string.
Declaration
SWIFT
func firstMatchInString(_string: String,
optionsoptions: NSMatchingOptions,
rangerange: NSRange) -> NSTextCheckingResult?OBJECTIVE-C
- (NSTextCheckingResult *)firstMatchInString:(NSString *)stringoptions:(NSMatchingOptions)optionsrange:(NSRange)rangeParameters
stringThe string to search.
optionsThe matching options to use. See NSMatchingOptions for possible values.
rangeThe range of the string to search.
Return Value
An
NSTextCheckingResultobject. This result gives the overall matched range via itsrangeproperty, and the range of each individual capture group via itsrangeAtIndex:method. The range {NSNotFound, 0} is returned if one of the capture groups did not participate in this particular match.Discussion
This is a convenience method that calls
enumerateMatchesInString:options:range:usingBlock:.Import Statement
import FoundationAvailability
Available in iOS 4.0 and later.
-
Returns the range of the first match of the regular expression within the specified range of the string.
Declaration
SWIFT
func rangeOfFirstMatchInString(_string: String,
optionsoptions: NSMatchingOptions,
rangerange: NSRange) -> NSRangeOBJECTIVE-C
- (NSRange)rangeOfFirstMatchInString:(NSString *)stringoptions:(NSMatchingOptions)optionsrange:(NSRange)rangeParameters
stringThe string to search.
optionsThe matching options to use. See NSMatchingOptions for possible values.
rangeThe range of the string to search.
Return Value
The range of the first match. Returns
{NSNotFound, 0}if no match is found.Discussion
This is a convenience method that calls
enumerateMatchesInString:options:range:usingBlock:.Import Statement
import FoundationAvailability
Available in iOS 4.0 and later.
-
-
Replaces regular expression matches within the mutable string using the template string.
Declaration
SWIFT
func replaceMatchesInString(_string: NSMutableString,
optionsoptions: NSMatchingOptions,
rangerange: NSRange,
withTemplatetemplate: String) -> IntOBJECTIVE-C
- (NSUInteger)replaceMatchesInString:(NSMutableString *)stringoptions:(NSMatchingOptions)optionsrange:(NSRange)rangewithTemplate:(NSString *)templateParameters
stringThe mutable string to search and replace values within.
optionsThe matching options to use. See NSMatchingOptions for possible values.
rangeThe range of the string to search.
templateThe substitution template used when replacing matching instances.
Return Value
The number of matches.
Discussion
See Flag Options for the format of
template.Import Statement
import FoundationAvailability
Available in iOS 4.0 and later.
-
Returns a new string containing matching regular expressions replaced with the template string.
Declaration
SWIFT
func stringByReplacingMatchesInString(_string: String,
optionsoptions: NSMatchingOptions,
rangerange: NSRange,
withTemplatetemplate: String) -> StringOBJECTIVE-C
- (NSString *)stringByReplacingMatchesInString:(NSString *)stringoptions:(NSMatchingOptions)optionsrange:(NSRange)rangewithTemplate:(NSString *)templateParameters
stringThe string to search for values within.
optionsThe matching options to use. See NSMatchingOptions for possible values.
rangeThe range of the string to search.
templateThe substitution template used when replacing matching instances.
Return Value
A string with matching regular expressions replaced by the template string.
Discussion
See Flag Options for the format of
template.Import Statement
import FoundationAvailability
Available in iOS 4.0 and later.
-
-
Returns a template string by adding backslash escapes as necessary to protect any characters that would match as pattern metacharacters
Declaration
Parameters
stringThe template string
Return Value
The escaped template string.
Discussion
Returns a string by adding backslash escapes as necessary to the given string, to escape any characters that would otherwise be treated as pattern metacharacters.
See Flag Options for the format of
template.Import Statement
import FoundationAvailability
Available in iOS 4.0 and later.
-
Returns a string by adding backslash escapes as necessary to protect any characters that would match as pattern metacharacters.
Declaration
Parameters
stringThe string.
Return Value
The escaped string.
Discussion
Returns a string by adding backslash escapes as necessary to the given string, to escape any characters that would otherwise be treated as pattern metacharacters.
See Flag Options for the format of
template.Import Statement
import FoundationAvailability
Available in iOS 4.0 and later.
-
-
Used to perform template substitution for a single result for clients implementing their own replace functionality.
Declaration
SWIFT
func replacementStringForResult(_result: NSTextCheckingResult,
inStringstring: String,
offsetoffset: Int,
templatetemplate: String) -> StringOBJECTIVE-C
- (NSString *)replacementStringForResult:(NSTextCheckingResult *)resultinString:(NSString *)stringoffset:(NSInteger)offsettemplate:(NSString *)templateParameters
resultThe result of the single match.
stringThe string from which the result was matched.
offsetThe offset to be added to the location of the result in the string.
templateSee Flag Options for the format of
template.Return Value
A replacement string.
Discussion
For clients implementing their own replace functionality, this is a method to perform the template substitution for a single result, given the string from which the result was matched, an offset to be added to the location of the result in the string (for example, in cases that modifications to the string moved the result since it was matched), and a replacement template.
This is an advanced method that is used only if you wanted to iterate through a list of matches yourself and do the template replacement for each one, plus maybe some other calculation that you want to do in code, then you would use this at each step.
Import Statement
import FoundationAvailability
Available in iOS 4.0 and later.
-
Constants
-
These constants define the regular expression options. These constants are used by the property
options,regularExpressionWithPattern:options:error:, andinitWithPattern:options:error:.Declaration
SWIFT
struct NSRegularExpressionOptions : RawOptionSetType { init(_value: UInt) var value: UInt static var CaseInsensitive: NSRegularExpressionOptions { get } static var AllowCommentsAndWhitespace: NSRegularExpressionOptions { get } static var IgnoreMetacharacters: NSRegularExpressionOptions { get } static var DotMatchesLineSeparators: NSRegularExpressionOptions { get } static var AnchorsMatchLines: NSRegularExpressionOptions { get } static var UseUnixLineSeparators: NSRegularExpressionOptions { get } static var UseUnicodeWordBoundaries: NSRegularExpressionOptions { get } }OBJECTIVE-C
enum { NSRegularExpressionCaseInsensitive = 1 << 0, NSRegularExpressionAllowCommentsAndWhitespace = 1 << 1, NSRegularExpressionIgnoreMetacharacters = 1 << 2, NSRegularExpressionDotMatchesLineSeparators = 1 << 3, NSRegularExpressionAnchorsMatchLines = 1 << 4, NSRegularExpressionUseUnixLineSeparators = 1 << 5, NSRegularExpressionUseUnicodeWordBoundaries = 1 << 6 }; typedef NSUInteger NSRegularExpressionOptions;Constants
-
NSRegularExpressionCaseInsensitiveMatch letters in the pattern independent of case.
Available in iOS 4.0 and later.
-
NSRegularExpressionAllowCommentsAndWhitespaceIgnore whitespace and #-prefixed comments in the pattern.
Available in iOS 4.0 and later.
-
NSRegularExpressionIgnoreMetacharactersTreat the entire pattern as a literal string.
Available in iOS 4.0 and later.
-
NSRegularExpressionDotMatchesLineSeparatorsAllow
.to match any character, including line separators.Available in iOS 4.0 and later.
-
NSRegularExpressionAnchorsMatchLinesAllow
^and$to match the start and end of lines.Available in iOS 4.0 and later.
-
NSRegularExpressionUseUnixLineSeparatorsTreat only
\nas a line separator (otherwise, all standard line separators are used).Available in iOS 4.0 and later.
-
NSRegularExpressionUseUnicodeWordBoundariesUse Unicode
TR#29to specify word boundaries (otherwise, traditional regular expression word boundaries are used).Available in iOS 4.0 and later.
Import Statement
import FoundationAvailability
Available in iOS 4.0 and later.
-
-
Set by the Block as the matching progresses, completes, or fails. Used by the method
enumerateMatchesInString:options:range:usingBlock:.Declaration
SWIFT
struct NSMatchingFlags : RawOptionSetType { init(_value: UInt) var value: UInt static var Progress: NSMatchingFlags { get } static var Completed: NSMatchingFlags { get } static var HitEnd: NSMatchingFlags { get } static var RequiredEnd: NSMatchingFlags { get } static var InternalError: NSMatchingFlags { get } }OBJECTIVE-C
enum { NSMatchingProgress = 1 << 0, NSMatchingCompleted = 1 << 1, NSMatchingHitEnd = 1 << 2, NSMatchingRequiredEnd = 1 << 3, NSMatchingInternalError = 1 << 4 }; typedef NSUInteger NSMatchingFlags;Constants
-
NSMatchingProgressSet when the Block is called to report progress during a long-running match operation.
Available in iOS 4.0 and later.
-
NSMatchingCompletedSet when the Block is called after matching has completed.
Available in iOS 4.0 and later.
-
NSMatchingHitEndSet when the current match operation reached the end of the search range.
Available in iOS 4.0 and later.
-
NSMatchingRequiredEndSet when the current match depended on the location of the end of the search range.
Available in iOS 4.0 and later.
-
NSMatchingInternalErrorSet when matching failed due to an internal error.
Available in iOS 4.0 and later.
Import Statement
import FoundationAvailability
Available in iOS 4.0 and later.
-
-
The matching options constants specify the reporting, completion and matching rules to the expression matching methods. These constants are used by all methods that search for, or replace values, using a regular expression.
Declaration
SWIFT
struct NSMatchingOptions : RawOptionSetType { init(_value: UInt) var value: UInt static var ReportProgress: NSMatchingOptions { get } static var ReportCompletion: NSMatchingOptions { get } static var Anchored: NSMatchingOptions { get } static var WithTransparentBounds: NSMatchingOptions { get } static var WithoutAnchoringBounds: NSMatchingOptions { get } }OBJECTIVE-C
enum { NSMatchingReportProgress = 1 << 0, NSMatchingReportCompletion = 1 << 1, NSMatchingAnchored = 1 << 2, NSMatchingWithTransparentBounds = 1 << 3, NSMatchingWithoutAnchoringBounds = 1 << 4 }; typedef NSUInteger NSMatchingOptions;Constants
-
NSMatchingReportProgressCall the Block periodically during long-running match operations. This option has no effect for methods other than
enumerateMatchesInString:options:range:usingBlock:. SeeenumerateMatchesInString:options:range:usingBlock:for a description of the constant in context.Available in iOS 4.0 and later.
-
NSMatchingReportCompletionCall the Block once after the completion of any matching. This option has no effect for methods other than
enumerateMatchesInString:options:range:usingBlock:. SeeenumerateMatchesInString:options:range:usingBlock:for a description of the constant in context.Available in iOS 4.0 and later.
-
NSMatchingAnchoredSpecifies that matches are limited to those at the start of the search range. See
enumerateMatchesInString:options:range:usingBlock:for a description of the constant in context.Available in iOS 4.0 and later.
-
NSMatchingWithTransparentBoundsSpecifies that matching may examine parts of the string beyond the bounds of the search range, for purposes such as word boundary detection, lookahead, etc. This constant has no effect if the search range contains the entire string. See
enumerateMatchesInString:options:range:usingBlock:for a description of the constant in context.Available in iOS 4.0 and later.
-
NSMatchingWithoutAnchoringBoundsSpecifies that
^and$will not automatically match the beginning and end of the search range, but will still match the beginning and end of the entire string. This constant has no effect if the search range contains the entire string. SeeenumerateMatchesInString:options:range:usingBlock:for a description of the constant in context.Available in iOS 4.0 and later.
Import Statement
import FoundationAvailability
Available in iOS 4.0 and later.
-
-
Copyright © 2014 Apple Inc. All rights reserved. Terms of Use | Privacy Policy | Updated: 2012-05-14
浙公网安备 33010602011771号