SwiftVerbalExpressions

Build Status Carthage compatible

简化 Swift 正则表达式的编写

SwiftVerbalExpressions 是一个 Swift 库,它可以帮助构建复杂的正则表达式 - 从优秀的 JavaScript VerbalExpressions 移植而来。

示例

这里有一些简单的例子,可以让你了解 VerbalExpressions 的工作方式

测试我们是否有一个有效的 URL

// Create an example of how to test for correctly formed URLs
let tester = VerEx()
    .startOfLine()
    .then("http")
    .maybe("s")
    .then("://")
    .maybe("www")
    .anythingBut(" ")
    .endOfLine()

// Create an example URL
let testMe = "https://www.google.com"

// Use test() method
if tester.test(testMe) {
    print("We have a correct URL") // This output will fire
}
else {
    print("The URL is incorrect")
}

// Use =~ operator
if testMe =~ tester {
    print("We have a correct URL") // This output will fire
}
else {
    print("The URL is incorrect")
}

prin(tester) // Outputs the actual expression used: "^(?:http)(?:s)?(?::\/\/)(?:www)?(?:[^ ]*)$"

替换字符串

let replaceMe = "Replace bird with a duck"

// Create an expression that seeks for word "bird"
let verEx = VerEx().find("bird")

// Execute the expression like a normal RegExp object
let result = verEx.replace(replaceMe, with: "duck")

print(result) // Outputs "Replace duck with a duck"

字符串替换的简写

let result2 = VerEx().find("red").replace("We have a red house", with: "blue")

print(result2) // Outputs "We have a blue house"

API 文档

您可以在他们的 wiki 上找到原始 JavaScript 仓库的文档。

贡献

克隆 repo 并 fork! 热烈欢迎 Pull Request!

感谢!

感谢 @jehna 提出了这个很棒的原创想法!
感谢 @kishikawakatsumi 贡献了 ObjectiveCVerbalExpressions,我从中借鉴了一些代码!

其他实现

您可以在 VerbalExpressions.github.io 上查看所有实现

安装和使用

此版本正在测试中,但它支持 Swift Package Manager。 因此,它可以包含在项目中,通过:

        .package(
            url: "https://github.com/VerbalExpressions/SwiftVerbalExpressions.git",
            from: "

并且

        .target(
            name: "YourProject",
            dependencies: ["VerbalExpressions"]),