NSRegularExpression

public extension NSRegularExpression

see also https://developer.apple.com/documentation/foundation/nsregularexpression // replace https://gist.github.com/watanabetoshinori/37f5bac79fc3f656f46c8711b6c78257 https://learnappmaking.com/regular-expressions-swift-string/ https://stackoverflow.com/questions/27880650/swift-extract-regex-matches https://www.hackingwithswift.com/articles/108/how-to-use-regular-expressions-in-swift https://www.hackingwithswift.com/articles/154/advanced-regular-expression-matching-with-nsregularexpression https://www.advancedswift.com/regex-capture-groups/

  • Ininializes a regular expression with the given pattern.

    Declaration

    Swift

    convenience init(with pattern: String, options: NSRegularExpression.Options = [])

    Parameters

    pattern

    String

    options

    0 or more of .caseInsensitive, .allowCommentsAndWhitespace, .ignoreMetacharacters, .dotMatchesLineSeparators, .anchorsMatchLines, .useUnixLineSeparators, .useUnicodeWordBoundaries,

  • Test whether the string matches the pattern.

    Declaration

    Swift

    func doesMatch(_ string: String) -> Bool

    Parameters

    string

    String

    Return Value

    true if the string matches the pattern

  • Find all matches found in the given string.

    Declaration

    Swift

    func findAll(in string: String) -> [String]

    Parameters

    string

    String

    Return Value

    [String] where the first element is the matching string and the following elements are the substrings that matched the capturing groups (if any)

  • Replace parts matched by pattern by replacement in string

    • Example “Hello World!”.replace(pattern: “Hello (.+)”, replacement: “Goodbye $1”) -> “Goodbye World!”

    Declaration

    Swift

    func replace(pattern: String, replacement: String, in string: String) -> String

    Parameters

    pattern

    String, pattrrn to match (may contain capture groups)

    replacement

    String (may contain backreferences $1,… to captured matches)

    string

    String, input

    Return Value

    String, modified