{"id":17962542,"url":"https://github.com/eneko/regex","last_synced_at":"2025-09-29T04:31:52.465Z","repository":{"id":54959631,"uuid":"186091864","full_name":"eneko/RegEx","owner":"eneko","description":"Easy regular expression data extraction in Swift","archived":false,"fork":false,"pushed_at":"2021-01-19T16:45:33.000Z","size":85,"stargazers_count":11,"open_issues_count":0,"forks_count":0,"subscribers_count":3,"default_branch":"main","last_synced_at":"2025-01-10T19:17:14.062Z","etag":null,"topics":["capture-groups","groups","iterator","regex","regular-expression","replacement","swift"],"latest_commit_sha":null,"homepage":"","language":"Swift","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/eneko.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2019-05-11T05:29:16.000Z","updated_at":"2023-08-23T18:59:49.000Z","dependencies_parsed_at":"2022-08-14T07:30:27.183Z","dependency_job_id":null,"html_url":"https://github.com/eneko/RegEx","commit_stats":null,"previous_names":[],"tags_count":3,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/eneko%2FRegEx","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/eneko%2FRegEx/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/eneko%2FRegEx/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/eneko%2FRegEx/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/eneko","download_url":"https://codeload.github.com/eneko/RegEx/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":234588046,"owners_count":18856856,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["capture-groups","groups","iterator","regex","regular-expression","replacement","swift"],"created_at":"2024-10-29T11:19:41.080Z","updated_at":"2025-09-29T04:31:52.119Z","avatar_url":"https://github.com/eneko.png","language":"Swift","readme":"![Swift 5.0+](https://img.shields.io/badge/Swift-5.0+-orange.svg)\n![Unit Tests](https://github.com/eneko/RegEx/workflows/Unit%20Test/badge.svg)\n[![codecov](https://codecov.io/gh/eneko/RegEx/branch/main/graph/badge.svg)](https://codecov.io/gh/eneko/RegEx)\n[![Swift Package Manager Compatible](https://img.shields.io/badge/spm-compatible-brightgreen.svg)](https://swift.org/package-manager)\n![Linux Compatible](https://img.shields.io/badge/linux-compatible%20🐧-brightgreen.svg)\n\n\n# RegEx\n`RegEx` is a thin `NSRegularExpression` wrapper for easier regular expression testing, data extraction, and replacement in Swift.\n\n![RegEx](/RegEx.png)\n\n#### Features\n- Test if a string matches the expression with `test()`\n- Determine the number of matches in a string with `numberOfMatches(in:)`\n- Retrieve all matches in a string with `matches(in:)`\n- Retrieve the first match without processing all matches with `firstMatch(in:)`\n- Efficiently **iterate over matches** with `iterator()` and `next()`\n- Replace matches with a template (including capture groups)\n- Replace matches one by one with **custom replacement logic** in a closure\n\nThe resulting `Match` structure contains the **full match**, any **captured groups**, and corresponding \nSwift **string ranges**.\n\nBy using `Range\u003cString.Index\u003e` and `Substring`, `RegEx.Match` is able to return all this information without\nduplicating data from the input string 👏\n\n## Usage\n\nGiven a string:\n```swift\nlet str = \"16^32=2^128\"\n```\n\nDefine an expression, for example to identify exponent notation (`^`) while \ncapturing exponent values:\n```swift\nlet expression = \"\\\\d+\\\\^(\\\\d+)\"\n```\n\nUse the regular expression:\n```swift\nlet regex = try RegEx(pattern: expression)\n\nregex.test(str) // true\n\nregex.numberOfMatches(in: str) // 2\n\nlet first = regex.firstMatch(in: str) // 1 match with 1 captured group\nfirst?.values // [\"16^32\", \"32\"] \n\nlet matches = regex.matches(in: str) // 2 matches with 1 captured group each\nmatches[0].values // [\"16^32\", \"32\"] \nmatches[1].values // [\"2^128\", \"128\"]\n```\n\n### Iterate over matches\n```swift\nlet iterator = regex.iterator(for: str) // Iterate over matches one by one\niterator.next()?.values // [\"16^32\", \"32\"] \niterator.next()?.values // [\"2^128\", \"128\"]\niterator.next()         // nil\n```\n\n### Replacement with Template\n```swift\nlet regex = try RegEx(pattern: #\"(\\d)(\\d)\"#)\nlet result = regex.replaceMatches(in: \"1234\", withTemplate: \"$2$1\")\n// result: 2143\n```\n\n### Replacement with Custom Logic\n```swift\nlet regex = try RegEx(pattern: #\"(\\w+)\\b\"#)\nlet result = regex.replaceMatches(in: \"Hello world!\")  { match in \n    let value = String(match.values[0] ?? \"\")\n    return String(value.reversed())\n}\n// result: olleH dlrow!\n```\n\n## Installation\n\nNo frameworks, just copy and paste!\n\n```swift\npublic class RegEx {\n    private let regex: NSRegularExpression\n\n    public init(pattern: String, options: NSRegularExpression.Options = []) throws {\n        regex = try NSRegularExpression(pattern: pattern, options: options)\n    }\n\n    public struct Match {\n        public let values: [Substring?]\n        public let ranges: [Range\u003cString.Index\u003e?]\n    }\n\n    public func numberOfMatches(in string: String, from index: String.Index? = nil) -\u003e Int {\n        let startIndex = index ?? string.startIndex\n        let range = NSRange(startIndex..., in: string)\n        return regex.numberOfMatches(in: string, range: range)\n    }\n\n    public func firstMatch(in string: String, from index: String.Index? = nil) -\u003e Match? {\n        let startIndex = index ?? string.startIndex\n        let range = NSRange(startIndex..., in: string)\n        let result = regex.firstMatch(in: string, range: range)\n        return result.flatMap { map(result: $0, in: string) }\n    }\n\n    public func matches(in string: String, from index: String.Index? = nil) -\u003e [Match] {\n        let startIndex = index ?? string.startIndex\n        let range = NSRange(startIndex..., in: string)\n        let results = regex.matches(in: string, range: range)\n        return results.map { map(result: $0, in: string) }\n    }\n\n    public func test(_ string: String) -\u003e Bool {\n        return firstMatch(in: string) != nil\n    }\n\n    func map(result: NSTextCheckingResult, in string: String) -\u003e Match {\n        let ranges = (0..\u003cresult.numberOfRanges).map { index in\n            Range(result.range(at: index), in: string)\n        }\n        let substrings = ranges.map { $0.flatMap { string[$0] }}\n        return Match(values: substrings, ranges: ranges)\n    }\n\n}\n\n\nextension RegEx {\n    public class Iterator: IteratorProtocol {\n        let regex: RegEx\n        let string: String\n        var current: RegEx.Match?\n\n        init(regex: RegEx, string: String) {\n            self.regex = regex\n            self.string = string\n            current = regex.firstMatch(in: string)\n        }\n\n        public func next() -\u003e RegEx.Match? {\n            defer {\n                current = current.flatMap {\n                    let index = $0.ranges[0]?.upperBound\n                    return self.regex.firstMatch(in: self.string, from: index)\n                }\n            }\n            return current\n        }\n    }\n\n    public func iterator(for string: String) -\u003e Iterator {\n        return Iterator(regex: self, string: string)\n    }\n}\n```\n\n### Swift Package Manager\nActually, I love unit tests, so I made this repo a Swift package that can be imported and used with\nSwift Package Manager.\n\nAdd the following code to your `Package.swift` :\n\n```\ndependencies: [\n    .package(url: \"https://github.com/eneko/RegEx.git\", from: \"0.1.0\")\n],\ntargets: {\n    .target(name: \"YourTarget\", dependencies: [\"RegEx\"])\n}\n```\n\n## Unit Tests\nIf curious, you can run the tests with `$ swift test` or `$ swift test --parallel`.\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Feneko%2Fregex","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Feneko%2Fregex","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Feneko%2Fregex/lists"}