SwiftRegularExpression

🏰 SwiftRegularExpression


Keywords
regexp, regular-expression, swift, swift-regexp, swift-regular-expression
License
MIT
Install
pod try SwiftRegularExpression

Documentation

swift-regular-expression

Swift REGEXP ( swift regular expression )

Install

pod 'SwiftRegularExpression'

or

// swift-tools-version:5.2
...

dependencies: [
    .package(name: "SwiftRegularExpression", url: "https://github.com/nerzh/swift-regular-expression.git", .upToNextMajor(from: "0.2.0"))
],
targets: [
    .target(
        name: "nameProject",
        dependencies: [
            .product(name: "SwiftRegularExpression", package: "SwiftRegularExpression")
        ]
    )
]

...

Usage

regexp: Find String matches

"hello world"[#"[^\s]+"#]
/// => String: "hello"
/// => String: "" if no matches

regexp: Return Bool

"hello world"[#"[^\s]+"#]
/// => Bool: true

regexp: Return Dictionary of numbered matches

"match".regexp(#"(ma)([\s\S]+)"#)
/// => Dictionary: [0: "match", 1: "ma", 2:"tch"]

regexp: Replace First match to value

"111 Hello 111".replaceFirst(#"\d+"#, "!!!") 
/// => String: "!!! Hello 111"
var str = "111 Hello 111"
str.replaceFirstSelf(#"\d+"#, "!!!")
/// Mutating "!!! Hello 111"
"111 Hello 111".replaceFirst(#"\d+"#) { (value) -> String in  
    return value == "111" ? "???" : value
}
///  => "??? Hello 111"
var str = "111 Hello 111"
str.replaceFirstSelf(#"\d+"#) { (value) -> String in  
    return value == "111" ? "???" : value
}
/// Mutate to "??? Hello 111"

regexp: Replace All match to values

"111 Hello 111".replace(#"\d+"#, "!!!")
/// =>  "!!! Hello !!!"
var str = "111 Hello 111"
str.replaceSelf(#"\d+"#, "!!!")
/// Mutate to  "!!! Hello !!!"
"111 Hello 222".replace(#"\d+"#) { (value) -> String in  
    return value == "222" ? "111" : value
}
/// =>  "111 Hello 111"
var str = "111 Hello 222"
str.replaceSelf(#"\d+"#) { (value) -> String in  return value == "222" ? "111" : value }
/// Mutate to "111 Hello 111"

regexp: Get All Match Ranges

"23 34".matchesWithRange(#"\d+"#)
/// => [Range<String.Index> : "23", Range<String.Index> : "34"]
"23 34".matchesWithRange(#"\d+"#)
/// => [[Range<String.Index> : "23", Range<String.Index> : "34"]]