Class: NSRegularExpression

Inherits:
NSObject show all

Overview

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.

Direct Known Subclasses

NSDataDetector

Instance Attribute Summary (collapse)

Class Method Summary (collapse)

Instance Method Summary (collapse)

Methods inherited from NSObject

#!, #!=, #!~, #, #==, #===, #=~, #Rational, #__callee__, #__method__, #__send__, #__type__, `, alloc, allocWithZone:, #autoContentAccessingProxy, autoload, autoload?, autorelease_pool, #awakeAfterUsingCoder:, binding, block_given?, caller, cancelPreviousPerformRequestsWithTarget:, cancelPreviousPerformRequestsWithTarget:selector:object:, catch, class, classFallbacksForKeyedArchiver, #classForCoder, #classForKeyedArchiver, classForKeyedUnarchiver, #clone, conformsToProtocol:, #copy, copyWithZone:, #dealloc, #define_singleton_method, description, display, #doesNotRecognizeSelector:, #dup, #enum_for, #eql?, #equal?, #extend, fail, #finalize, format, #forwardInvocation:, #forwardingTargetForSelector:, framework, #freeze, #frozen?, getpass, gets, global_variables, #init, initialize, #initialize_clone, #initialize_copy, #initialize_dup, #inspect, instanceMethodForSelector:, instanceMethodSignatureForSelector:, #instance_eval, #instance_exec, #instance_of?, #instance_variable_defined?, #instance_variable_get, #instance_variable_set, #instance_variables, instancesRespondToSelector:, isSubclassOfClass:, #is_a?, iterator?, #kind_of?, lambda, load, load_bridge_support_file, load_plist, local_variables, loop, #method, #methodForSelector:, #methodSignatureForSelector:, #methods, #mutableCopy, mutableCopyWithZone:, new, #nil?, open, p, #performSelector:onThread:withObject:waitUntilDone:, #performSelector:onThread:withObject:waitUntilDone:modes:, #performSelector:withObject:afterDelay:, #performSelector:withObject:afterDelay:inModes:, #performSelectorInBackground:withObject:, #performSelectorOnMainThread:withObject:waitUntilDone:, #performSelectorOnMainThread:withObject:waitUntilDone:modes:, print, printf, #private_methods, proc, #protected_methods, #public_method, #public_methods, #public_send, putc, puts, raise, rand, readline, readlines, #replacementObjectForCoder:, #replacementObjectForKeyedArchiver:, require, resolveClassMethod:, resolveInstanceMethod:, #respond_to?, #respond_to_missing?, select, #send, setVersion:, #singleton_methods, sprintf, srand, superclass, #taint, #tainted?, #tap, test, throw, #to_plist, #to_s, trace_var, trap, #trust, #untaint, untrace_var, #untrust, #untrusted?, version

Constructor Details

This class inherits a constructor from NSObject

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class NSObject

Instance Attribute Details

- (Integer) numberOfCaptureGroups (readonly)

Returns the number of capture groups in the regular expression. (read-only) 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 n for $n in templates, and it determines the number of ranges in the returned NSTextCheckingResult instances returned in the match... methods. An exception will be generated if you attempt to access a result with an index value exceeding numberOfCaptureGroups-1.

Returns:

- (NSRegularExpressionOptions) options (readonly)

Returns the options used when the regular expression option was created. (read-only) 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.

Returns:

  • (NSRegularExpressionOptions)

- (String) pattern (readonly)

Returns the regular expression pattern. (read-only)

Returns:

Class Method Details

+ (String) escapedPatternForString(string)

Returns a string by adding backslash escapes as necessary to protect any characters that would match as pattern metacharacters. 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.

Parameters:

  • string (String)

    The string.

Returns:

  • (String)

    The escaped string.

+ (String) escapedTemplateForString(string)

Returns a template string by adding backslash escapes as necessary to protect any characters that would match as pattern metacharacters. 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.

Parameters:

  • string (String)

    The template string.

Returns:

  • (String)

    The escaped template string.

+ (NSRegularExpression) regularExpressionWithPattern(pattern, options:options, error:error)

Creates an NSRegularExpression instance with the specified regular expression pattern and options.

Parameters:

  • pattern (String)

    The regular expression pattern to compile.

  • options (NSRegularExpressionOptions)

    The matching options. See “NSRegularExpressionOptions” for possible values. The values can be combined using the C-bitwise OR operator.

  • error (Pointer)

    An out value that returns any error encountered during initialization. Returns nil if the regular expression pattern is invalid.

Returns:

Instance Method Details

- (Object) enumerateMatchesInString(string, options:options, range:range, usingBlock:block)

Enumerates the string allowing the Block to handle each regular expression match. 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-nil result and the appropriate flags. The client may then stop the operation by setting the contents of stop to YES. The stop argument is an out-only argument. You should only ever set this Boolean to YES within the Block.If the NSMatchingReportProgress matching option is specified, the Block will also be called periodically during long-running match operations, with nil result and NSMatchingProgress matching flag set in the Block’s flags parameter, at which point the client may again stop the operation by setting the contents of stop to YES. If the NSMatchingReportCompletion matching option is specified, the Block object will be called once after matching is complete, with nil result and the NSMatchingCompleted matching flag is set in the flags passed to the Block, plus any additional relevant “NSMatchingFlags” from among NSMatchingHitEnd, NSMatchingRequiredEnd, or NSMatchingInternalError. NSMatchingProgress and NSMatchingCompleted matching flags have no effect for methods other than this method.The NSMatchingHitEnd matching flag is set in the flags passed to the Block if the current match operation reached the end of the search range. The NSMatchingRequiredEnd matching flag is set in the flags passed 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 flags passed 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, and NSMatchingWithoutAnchoringBounds regular expression options, specified in the options property specified when the regular expression instance is created, can apply to any match or replace method. If NSMatchingAnchored matching option is specified, matches are limited to those at the start of the search range. If NSMatchingWithTransparentBounds matching 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 NSMatchingWithoutAnchoringBounds matching 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. NSMatchingWithTransparentBounds and NSMatchingWithoutAnchoringBounds matching options have no effect if the search range covers the entire string.

Parameters:

  • string

    The string.

  • options

    The matching options to report. See “NSMatchingOptions” for the supported values.

  • range

    The range of the string to test.

  • block

    The Block enumerates the matches of the regular expression in the string..The block takes three arguments:resultAn NSTextCheckingResult specifying the match. This result gives the overall matched range via its range property, and the range of each individual capture group via its rangeAtIndex: method. The range 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 YES to stop further processing of the array. The stop argument is an out-only argument. You should only ever set this Boolean to YES within the Block.The Block returns void.

  • result

    An NSTextCheckingResult specifying the match. This result gives the overall matched range via its range property, and the range of each individual capture group via its rangeAtIndex: method. The range 0 is returned if one of the capture groups did not participate in this particular match.

  • flags

    The current state of the matching progress. See “NSMatchingFlags” for the possible values.

  • stop

    A reference to a Boolean value. The Block can set the value to YES to stop further processing of the array. The stop argument is an out-only argument. You should only ever set this Boolean to YES within the Block.

Returns:

- (NSTextCheckingResult) firstMatchInString(string, options:options, range:range)

Returns the first match of the regular expression within the specified range of the string. This is a convenience method that calls enumerateMatchesInString:options:range:usingBlock:.

Parameters:

  • string (String)

    The string to search.

  • options (NSMatchingOptions)

    The matching options to use. See “NSMatchingOptions” for possible values.

  • range (NSRange)

    The range of the string to search.

Returns:

  • (NSTextCheckingResult)

    An NSTextCheckingResult object. This result gives the overall matched range via its range property, and the range of each individual capture group via its rangeAtIndex: method. The range 0 is returned if one of the capture groups did not participate in this particular match.

- (Object) initWithPattern(pattern, options:options, error:error)

Returns an initialized NSRegularExpression instance with the specified regular expression pattern and options.

Parameters:

  • pattern (String)

    The regular expression pattern to compile.

  • options (NSRegularExpressionOptions)

    The regular expression options that are applied to the expression during matching. See “NSRegularExpressionOptions” for possible values.

  • error (Pointer)

    An out value that returns any error encountered during initialization. Returns nil if the regular expression pattern is invalid.

Returns:

- (Array) matchesInString(string, options:options, range:range)

Returns an array containing all the matches of the regular expression in the string. This is a convenience method that calls enumerateMatchesInString:options:range:usingBlock: passing the appropriate string, options, and range..

Parameters:

  • string (String)

    The string to search.

  • options (NSMatchingOptions)

    The matching options to use. See “NSMatchingOptions” for possible values.

  • range (NSRange)

    The range of the string to search.

Returns:

  • (Array)

    An array of NSTextCheckingResult objects. Each result gives the overall matched range via its range property, and the range of each individual capture group via its rangeAtIndex: method. The range 0 is returned if one of the capture groups did not participate in this particular match.

- (Integer) numberOfMatchesInString(string, options:options, range:range)

Returns the number of matches of the regular expression within the specified range of the string. This is a convenience method that calls enumerateMatchesInString:options:range:usingBlock:.

Parameters:

  • string (String)

    The string to search.

  • options (NSMatchingOptions)

    The matching options to use. See “NSMatchingOptions” for possible values.

  • range (NSRange)

    The range of the string to search.

Returns:

  • (Integer)

    The number of matches of the regular expression.

- (NSRange) rangeOfFirstMatchInString(string, options:options, range:range)

Returns the range of the first match of the regular expression within the specified range of the string. This is a convenience method that calls enumerateMatchesInString:options:range:usingBlock:.

Parameters:

  • string (String)

    The string to search.

  • options (NSMatchingOptions)

    The matching options to use. See “NSMatchingOptions” for possible values.

  • range (NSRange)

    The range of the string to search.

Returns:

  • (NSRange)

    The range of the first match. Returns 0 if no match is found.

- (Integer) replaceMatchesInString(string, options:options, range:range, withTemplate:template)

Replaces regular expression matches within the mutable string the using the template string. See “Flag Options” for the format of template.

Parameters:

  • string (String)

    The mutable string to search and replace values within.

  • options (NSMatchingOptions)

    The matching options to use. See “NSMatchingOptions” for possible values.

  • range (NSRange)

    The range of the string to search.

  • template (String)

    The substitution template used when replacing matching instances.

Returns:

  • (Integer)

    The number of matches.

- (String) replacementStringForResult(result, inString:string, offset:offset, template:template)

Used to perform template substitution for a single result for clients implementing their own replace functionality. 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.

Parameters:

  • result (NSTextCheckingResult)

    The result of the single match.

  • string (String)

    The string from which the result was matched.

  • offset (Integer)

    The offset to be added to the location of the result in the string.

  • template (String)

    See “Flag Options” for the format of template.

Returns:

  • (String)

    A replacement string.

- (String) stringByReplacingMatchesInString(string, options:options, range:range, withTemplate:template)

Returns a new string containing matching regular expressions replaced with the template string. See “Flag Options” for the format of template.

Parameters:

  • string (String)

    The string to search for values within.

  • options (NSMatchingOptions)

    The matching options to use. See “NSMatchingOptions” for possible values.

  • range (NSRange)

    The range of the string to search.

  • template (String)

    The substitution template used when replacing matching instances.

Returns:

  • (String)

    A string with matching regular expressions replaced by the template string.