正则表达式

强大的模式匹配。

用法

创建

// Use `Regex.init(_:)` to build a regex from a static pattern

let greeting = Regex("hello (world|universe)")

// Use `Regex.init(string:)` to construct a regex from dynamic data, and
// gracefully handle invalid input

var validations: [String: Regex]

for (name, pattern) in config.loadValidations() {
  do {
    validations[name] = try Regex(string: pattern)
  } catch {
    print("error building validation \(name): \(error)")
  }
}

匹配

if greeting.matches("hello universe!") {
  print("wow, you're friendly!")
}

模式匹配

switch someTextFromTheInternet {
case Regex("DROP DATABASE (.+)"):
  // TODO: patch security hole
default:
  break
}

捕获

let greeting = Regex("hello (world|universe|swift)")

if let subject = greeting.firstMatch(in: "hello swift")?.captures[0] {
  print("ohai \(subject)")
}

查找和替换

"hello world".replacingFirst(matching: "h(ello) (\\w+)", with: "H$1, $2!")
// "Hello, world!"

访问上次匹配结果

switch text {
case Regex("hello (\\w+)"):
  if let friend = Regex.lastMatch?.captures[0] {
    print("lovely to meet you, \(friend)!")
  }
case Regex("goodbye (\\w+)"):
  if let traitor = Regex.lastMatch?.captures[0] {
    print("so sorry to see you go, \(traitor)!")
  }
default:
  break
}

选项

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"]

解码

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!/)

范围

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"]

安装

Regex 支持 Swift 4.2 及以上版本,在所有 Swift 平台上均可使用。

Swift 包管理器

将依赖项添加到您的 Package.swift 文件中

let package = Package(
  name: "MyPackage",
  dependencies: [
    // other dependencies...
    .package(url: "https://github.com/sharplet/Regex.git", from: "2.1.0"),
  ]
)

Carthage

将其放入您的 Cartfile 文件中

github "sharplet/Regex" ~> 2.1

CocoaPods

将其放入您的 Podfile 文件中

pod "STRegex", "~> 2.1"

贡献

请参阅 CONTRIBUTING.md

开发设置

Swift 包管理器

构建并运行测试

swift test

# or just

rake test:package

如果您使用的是 Mac,则通过 Docker for Mac 支持在 Linux 上进行测试。设置 Docker 后,启动 Linux shell

rake docker

并通过 Swift 包管理器运行测试。

Xcode

建议使用 xcpretty,以美化测试输出

gem install xcpretty

然后运行测试

# one of
rake test:osx
rake test:ios
rake test:tvos

格式化和 Linting

Regex 使用 SwiftFormat 来保持一致的代码格式。

Regex 使用 SwiftLint 来验证代码风格。SwiftLint 使用 Hound CI 自动对 pull request 运行。

当提交 pull request 时,非常感谢您运行这些工具并解决任何问题!

brew bundle
swiftformat .
swiftlint

许可证

请参阅 LICENSE.txt