RegularExpression

open class RegularExpression

See NSRegularExpression for details on pattern syntax.

  • The options specified during creation.

    Declaration

    Swift

    public let options: Options
  • The pattern specified during creation.

    Declaration

    Swift

    public private(set) lazy var pattern: String { get set }
  • The number of capture groups in the pattern.

    Declaration

    Swift

    public private(set) lazy var numberOfCaptureGroups: Int { get set }
  • Returns an initialized RegularExpression instance with the specified regular expression pattern and options. If an error occurs then nil is returned.

    See NSRegularExpression for details on pattern syntax.

    Declaration

    Swift

    public init?<S>(pattern: S, options: Options = [], error: inout Error?) where S : StringProtocol

    Parameters

    pattern

    the regular expression pattern.

    options

    the options.

    error

    if initialization fails then this parameter will be set to the error.

  • Returns an initialized RegularExpression instance with the specified regular expression pattern and options. If an error occurs then nil is returned.

    Declaration

    Swift

    @inlinable
    public convenience init?<S>(pattern: S, options: Options = []) where S : StringProtocol

    Parameters

    pattern

    the regular expression pattern.

    options

    the options.

  • 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. You typically use this method to match on a particular string within a larger pattern.

    For example, the string “(N/A)” contains the pattern metacharacters (, /, and ). The result of adding backslash escapes to this string is “\(N\/A\)”.

    Declaration

    Swift

    @inlinable
    public class func escapedPattern<S>(for string: S) -> String where S : StringProtocol

    Parameters

    string

    the string or substring.

    Return Value

    the escaped 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. You typically use this method to match on a particular string within a larger pattern.

    For example, the string “(N/A)” contains the pattern metacharacters (, /, and ). The result of adding backslash escapes to this string is “\(N\/A\)”.

    See Flag Options for the format of the resulting template string.

    Declaration

    Swift

    @inlinable
    public class func escapedTemplate<S>(for string: S) -> String where S : StringProtocol

    Parameters

    string

    the template string or substring.

    Return Value

    the escaped template string.

  • Returns the number of matches of the regular expression within the specified range of the string.

    Declaration

    Swift

    @inlinable
    public func numberOfMatches(in str: String, options: MatchingOptions = [], range: Range<String.Index>) -> Int

    Parameters

    str

    the search string.

    options

    The matching options to use. See RegularExpression.MatchingOptions for possible values.

    range

    the range of the string to search.

    Return Value

    the number of matches of the regular expression.

  • Returns the number of matches of the regular expression within the specified range of the string.

    Declaration

    Swift

    @inlinable
    public func numberOfMatches<S>(in str: S, options: MatchingOptions = []) -> Int where S : StringProtocol

    Parameters

    str

    the search string or substring.

    options

    The matching options to use. See RegularExpression.MatchingOptions for possible values.

    Return Value

    the number of matches of the regular expression.

  • Returns the range of the first match.

    Declaration

    Swift

    @inlinable
    public func rangeOfFirstMatch(in str: String, options: MatchingOptions = [], range: Range<String.Index>) -> Range<String.Index>?

    Parameters

    str

    the search string.

    options

    The matching options to use. See RegularExpression.MatchingOptions for possible values.

    range

    the range of the string to search.

    Return Value

    the range of the first match of nil if the match was not found.

  • Returns the range of the first match.

    Declaration

    Swift

    @inlinable
    public func rangeOfFirstMatch<S>(in str: S, options: MatchingOptions = []) -> Range<String.Index>? where S : StringProtocol

    Parameters

    str

    the search string or substring.

    options

    The matching options to use. See RegularExpression.MatchingOptions for possible values.

    Return Value

    the range of the first match of nil if the match was not found.

  • Returns the first RegularExpression.Match found in the search string.

    Declaration

    Swift

    @inlinable
    public func firstMatch(in str: String, options: MatchingOptions = [], range: Range<String.Index>) -> Match?

    Parameters

    str

    the search string.

    options

    The matching options to use. See RegularExpression.MatchingOptions for possible values.

    range

    the range of the string to search.

    Return Value

    the first RegularExpression.Match found in the search string or nil if the match was not found.

  • Returns the first RegularExpression.Match found in the search string.

    Declaration

    Swift

    @inlinable
    public func firstMatch<S>(in str: S, options: MatchingOptions = []) -> Match? where S : StringProtocol

    Parameters

    str

    the search string or substring.

    options

    The matching options to use. See RegularExpression.MatchingOptions for possible values.

    Return Value

    the first RegularExpression.Match found in the search string or nil if the match was not found.

  • Returns all of the RegularExpression.Matchs found in the search string.

    Declaration

    Swift

    @inlinable
    public func matches(in str: String, options: MatchingOptions = [], range: Range<String.Index>) -> [Match]

    Parameters

    str

    the search string.

    options

    The matching options to use. See RegularExpression.MatchingOptions for possible values.

    range

    the range of the string to search.

    Return Value

    an array of RegularExpression.Matchs found in the search string or an empty array if the match was not found.

  • Returns all of the RegularExpression.Matchs found in the search string.

    Declaration

    Swift

    @inlinable
    public func matches<S>(in str: S, options: MatchingOptions = []) -> [Match] where S : StringProtocol

    Parameters

    str

    the search string or substring.

    options

    The matching options to use. See RegularExpression.MatchingOptions for possible values.

    Return Value

    an array of RegularExpression.Matchs found in the search string or an empty array if the match was not found.

  • Enumerates the string allowing the Block to handle each regular expression match.

    NOTE: Having this as a throwing function rather than a rethrowing function is not ideal but given that NSRegularExpression doesn’t allow the closure to throw anything sort of removes that option from us. At least I haven’t found an easy way around it. So I decided to have to have this method throws and in the future, if we can fix this issue, make it rethrows then.

    This method is the fundamental matching method for regular expressions and is suitable for overriding by subclasses. 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 match and the appropriate flags. The client may then stop the operation by returning true from the block instead of false.

    If the RegularExpression.MatchingOptions.reportProgress matching option is specified, the Block will also be called periodically during long-running match operations, with nil result and progress matching flag set in the Block’s flags parameter, at which point the client may again stop the operation by returning true instead of false.

    If the RegularExpression.MatchingOptions.reportCompletion matching option is specified, the Block object will be called once after matching is complete, with nil result and the completed matching flag is set in the flags passed to the Block, plus any additional relevant RegularExpression.MatchingFlags from among RegularExpression.MatchingFlags.hitEnd, RegularExpression.MatchingFlags.requiredEnd, or RegularExpression.MatchingFlags.internalError.

    RegularExpression.MatchingFlags.progress and RegularExpression.MatchingFlags.completed matching flags have no effect for methods other than this method.

    The RegularExpression.MatchingFlags.hitEnd matching flag is set in the flags passed to the Block if the current match operation reached the end of the search range. The RegularExpression.MatchingFlags.requiredEnd 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 RegularExpression.MatchingFlags 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 RegularExpression.Options.anchored, RegularExpression.Options.withTransparentBounds, and RegularExpression.Options.withoutAnchoringBounds 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 RegularExpression.Options.anchored matching option is specified, matches are limited to those at the start of the search range.

    If RegularExpression.Options.withTransparentBounds 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 RegularExpression.Options.withoutAnchoringBounds 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.

    RegularExpression.Options.withTransparentBounds and RegularExpression.Options.withoutAnchoringBounds matching options have no effect if the search range covers the entire string.

    Declaration

    Swift

    @inlinable
    public func forEachMatch(in str: String, options: MatchingOptions = [], range: Range<String.Index>, using block: (Match?, MatchingFlags, inout Bool) throws -> Void) rethrows

    Parameters

    str

    the search string.

    options

    The matching options to report. See RegularExpression.MatchingOptions for the supported values.

    range

    the range of the string to search.

    block

    the Block that is called for each match found in the search string. The Block takes two (2) parameters:

    match
    An instance of RegularExpression.Match or nil if the Block is simply being called with the flags RegularExpression.MatchingFlags.completed, RegularExpression.MatchingFlags.hitEnd, or RegularExpression.MatchingFlags.internalError
    flags
    An array of RegularExpression.MatchingFlags.
    The closure returns true to stop the enumeration or false to continue to the next match.

  • Enumerates the string allowing the Block to handle each regular expression match.

    NOTE: Having this as a throwing function rather than a rethrowing function is not ideal but given that NSRegularExpression doesn’t allow the closure to throw anything sort of removes that option from us. At least I haven’t found an easy way around it. So I decided to have to have this method throws and in the future, if we can fix this issue, make it rethrows then.

    This method is the fundamental matching method for regular expressions and is suitable for overriding by subclasses. 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 match and the appropriate flags. The client may then stop the operation by returning true from the block instead of false.

    If the RegularExpression.MatchingOptions.reportProgress matching option is specified, the Block will also be called periodically during long-running match operations, with nil result and progress matching flag set in the Block’s flags parameter, at which point the client may again stop the operation by returning true instead of false.

    If the RegularExpression.MatchingOptions.reportCompletion matching option is specified, the Block object will be called once after matching is complete, with nil result and the completed matching flag is set in the flags passed to the Block, plus any additional relevant RegularExpression.MatchingFlags from among RegularExpression.MatchingFlags.hitEnd, RegularExpression.MatchingFlags.requiredEnd, or RegularExpression.MatchingFlags.internalError.

    RegularExpression.MatchingFlags.progress and RegularExpression.MatchingFlags.completed matching flags have no effect for methods other than this method.

    The RegularExpression.MatchingFlags.hitEnd matching flag is set in the flags passed to the Block if the current match operation reached the end of the search range. The RegularExpression.MatchingFlags.requiredEnd 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 RegularExpression.MatchingFlags 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 RegularExpression.Options.anchored, RegularExpression.Options.withTransparentBounds, and RegularExpression.Options.withoutAnchoringBounds 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 RegularExpression.Options.anchored matching option is specified, matches are limited to those at the start of the search range.

    If RegularExpression.Options.withTransparentBounds 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 RegularExpression.Options.withoutAnchoringBounds 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.

    RegularExpression.Options.withTransparentBounds and RegularExpression.Options.withoutAnchoringBounds matching options have no effect if the search range covers the entire string.

    Declaration

    Swift

    @inlinable
    public func forEachMatch<S>(in str: S, options: MatchingOptions = [], using block: (Match?, MatchingFlags, inout Bool) throws -> Void) rethrows where S : StringProtocol

    Parameters

    str

    the search string or substring.

    options

    The matching options to report. See RegularExpression.MatchingOptions for the supported values.

    block

    the Block that is called for each match found in the search string. The Block takes two (2) parameters:

    match
    An instance of RegularExpression.Match or nil if the Block is simply being called with the flags RegularExpression.MatchingFlags.completed, RegularExpression.MatchingFlags.hitEnd, or RegularExpression.MatchingFlags.internalError
    flags
    An array of RegularExpression.MatchingFlags.
    The closure returns true to stop the enumeration or false to continue to the next match.

  • 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 subclasses. 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 an array of the RegularExpression.Groups representing each capture group. The client may then stop the operation by returning true from the block instead of false.

    Declaration

    Swift

    @inlinable
    public func forEachMatchGroup(in str: String, options: MatchingOptions = [], range: Range<String.Index>, using block: ([Group], inout Bool) throws -> Void) rethrows

    Parameters

    str

    the search string.

    options

    The matching options to report. See RegularExpression.MatchingOptions for the supported values.

    range

    the range of the string to search.

    block

    the closure that is called for each match found in the search string. The closure takes one parameter which is an array of RegularExpression.Group objects representing each capture group and returns true to stop the enumeration or false to continue to the next match.

  • 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 subclasses. 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 an array of the RegularExpression.Groups representing each capture group. The client may then stop the operation by returning true from the block instead of false.

    Declaration

    Swift

    @inlinable
    public func forEachMatchGroup<S>(in str: S, options: MatchingOptions = [], using block: ([Group], inout Bool) throws -> Void) rethrows where S : StringProtocol

    Parameters

    str

    the search string or substring.

    options

    The matching options to report. See RegularExpression.MatchingOptions for the supported values.

    block

    the closure that is called for each match found in the search string. The closure takes one parameter which is an array of RegularExpression.Group objects representing each capture group and returns true to stop the enumeration or false to continue to the next match.

  • Enumerates the string allowing the Block to handle each regular expression match.

    Declaration

    Swift

    @inlinable
    public func forEachMatchString(in str: String, options: MatchingOptions = [], range: Range<String.Index>, using block: ([String?], inout Bool) throws -> Void) rethrows

    Parameters

    str

    the search string.

    options

    The matching options to report. See RegularExpression.MatchingOptions for the supported values.

    range

    the range of the string to search.

    block

    the closure that is called for each match found in the search string. The closure takes one parameter which is an array of Strings representing each capture group and returns true to stop the enumeration or false to continue to the next match. Any of the strings in the array may be nil if that capture group did not participate in the match.

  • Enumerates the string allowing the Block to handle each regular expression match.

    Declaration

    Swift

    @inlinable
    public func forEachMatchString<S>(in str: S, options: MatchingOptions = [], using block: ([String?], inout Bool) throws -> Void) rethrows where S : StringProtocol

    Parameters

    str

    the search string or substring.

    options

    The matching options to report. See RegularExpression.MatchingOptions for the supported values.

    block

    the closure that is called for each match found in the search string. The closure takes one parameter which is an array of Strings representing each capture group and returns true to stop the enumeration or false to continue to the next match. Any of the strings in the array may be nil if that capture group did not participate in the match.

  • RegularExpression also provides a find-and-replace method for strings. The replacement 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 itself.

    Declaration

    Swift

    @inlinable
    public func stringByReplacingMatches(in str: String, options: MatchingOptions = [], range: Range<String.Index>, withTemplate templ: String) -> (String, Int)

    Parameters

    str

    the string.

    options

    the match options.

    range

    the range of the string to search in. If nil then the entire string will be searched.

    templ

    the replacement template.

    Return Value

    a tuple with the modified string and the number of replacements made.

  • RegularExpression also provides a find-and-replace method for strings. The replacement 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 itself.

    Declaration

    Swift

    @inlinable
    public func stringByReplacingMatches<S>(in str: S, options: MatchingOptions = [], withTemplate templ: String) -> (String, Int) where S : StringProtocol

    Parameters

    str

    the string or substring.

    options

    the match options.

    templ

    the replacement template.

    Return Value

    a tuple with the modified string and the number of replacements made.

  • This method will perform a find-and-replace on the provided string by calling the closure for each match found in the source string and replacing it with the string returned by the closure.

    Throws

    if the closure throws an error.

    Declaration

    Swift

    @inlinable
    public func stringByReplacingMatches(in str: String, options: MatchingOptions = [], range: Range<String.Index>, using block: (Match) throws -> String) rethrows -> (String, Int)

    Parameters

    str

    the source string.

    options

    the match options.

    range

    the range of the string to search in. If nil then the entire string will be searched.

    block

    the closure that will return the replacement string. It is called once for each match found in the source string.

    Return Value

    a tuple with the modified string and the number of replacements made.

  • This method will perform a find-and-replace on the provided string by calling the closure for each match found in the source string and replacing it with the string returned by the closure.

    Throws

    if the closure throws an error.

    Declaration

    Swift

    @inlinable
    public func stringByReplacingMatches<S>(in str: S, options: MatchingOptions = [], using block: (Match) throws -> String) rethrows -> (String, Int) where S : StringProtocol

    Parameters

    str

    the source string or substring.

    options

    the match options.

    block

    the closure that will return the replacement string. It is called once for each match found in the source string.

    Return Value

    a tuple with the modified string and the number of replacements made.