Skip to content

Commit

Permalink
Merge pull request #61 from sharplet/examplify
Browse files Browse the repository at this point in the history
Add some examples for new 1.1.0 features
  • Loading branch information
sharplet committed Aug 4, 2017
2 parents 9b6a89b + 5594bdc commit 0b18d20
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 1 deletion.
40 changes: 39 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,12 +83,50 @@ default:
Options:

```swift
let totallyUniqueExamples = Regex("^(hello|foo).*$", options: [.IgnoreCase, .AnchorsMatchLines])
let totallyUniqueExamples = Regex("^(hello|foo).*$", options: [.ignoreCase, .anchorsMatchLines])
let multilineText = "hello world\ngoodbye world\nFOOBAR\n"
let matchingLines = totallyUniqueExamples.allMatches(in: multilineText).map { $0.matchedString }
// ["hello world", "FOOBAR"]
```

Decode:

```swift
let json = """
[
{
"name" : "greeting",
"pattern" : "^(\\\\w+) world!$"
}
]
""".data(using: .utf8)!

struct Validation: Codable {
var name: String
var pattern: Regex
}

let decoder = JSONDecoder()
try decoder.decode(Validation.self, from: json)
// Validation(name: "greeting", pattern: /^(\w+) world!/)
```

Ranges:

```swift
let lyrics = """
So it's gonna be forever
Or it's gonna go down in flames
"""

let possibleEndings = Regex("it's gonna (.+)")
.allMatches(in: lyrics)
.flatMap { $0.captureRanges[0] }
.map { lyrics[$0] }

// it's gonna: ["be forever", "go down in flames"]
```



## Installation
Expand Down
16 changes: 16 additions & 0 deletions Tests/RegexTests/RegexSpec.swift
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,22 @@ final class RegexSpec: QuickSpec {
expect(location).to(equal(2))
expect(length).to(equal(1))
}

#if swift(>=3.2)
it("validates the README example for capture ranges") {
let lyrics = """
So it's gonna be forever
Or it's gonna go down in flames
"""

let possibleEndings = Regex("it's gonna (.+)")
.allMatches(in: lyrics)
.flatMap { $0.captureRanges[0] }
.map { lyrics[$0] }

expect(possibleEndings) == ["be forever", "go down in flames"]
}
#endif
}

describe("matching at line anchors") {
Expand Down

0 comments on commit 0b18d20

Please sign in to comment.