SwiftVerbalExpressions 是一个 Swift 库,它可以帮助构建复杂的正则表达式 - 从优秀的 JavaScript VerbalExpressions 移植而来。
这里有一些简单的例子,可以让你了解 VerbalExpressions 的工作方式
// 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"
您可以在他们的 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"]),