If you are developing cross platform (macOS and Linux) command line apps, and
you want to use Regular expressions, Regex is just what you need.
You can use Regex with Guaka to create
aweseome command line applications.
- Checking if a string matches a pattern.
let r = try! Regex(pattern: "Hello [a-z]+ame")
r.matches("Hello Name")- Capture a string with a regex capture group
let r = try! Regex(pattern: "Hello (.*) name")
let result = r.captures(string: "Hello mr name")result is an array of CaptureResult
- Using the
~=operator
// Regex ~= String
let value = try! Regex(pattern: "Hello [a-z]+ame") ~= "Hello Name"
// value is true
// String ~= Regex
let value = "Hello Name" ~= try! Regex(pattern: "Hello [a-z]+ame")
// value is true- Using regex matching with switch
switch "Hello I am on swift" {
case try! Regex(pattern: "Hello [a-z] am .*"):
// First
case try! Regex(pattern: ".*"):
// Second
}The first passing regex will be matched. In the example above, the first case is matched.
Replace a pattern with a string:
"This string is wrong".replacing(pattern: "w.*g", withString: "right")
// "This string is right"CaptureResult represent a captured string, it contains:
originalStringthe original stringstartIndexthe capture start indexendIndexthe capture end indexrangethe range of the captured stringstringthe captured string
RegexOptions optionset can be passed when initilaizing a Regex object. For
a discussion on the meaning of these flags, refer to GNU regex
documentation
matches(_:options:) accepts the MatchOptions option set. For a discussion
on the meaning of these flags, refer to GNU regex
documentation
You can install Regex using Swift package manager (SPM) and carthage
Add Regex as dependency in your Package.swift
import PackageDescription
let package = Package(name: "YourPackage",
dependencies: [
.Package(url: "https://github.com/getGuaka/Regex.git", majorVersion: 0),
]
)github "getGuaka/Regex"
Tests can be found here.
Run them with
swift test
Just send a PR! We don't bite ;)