# Regex

[Swift]() ⟩ Regex

{% tabs %}
{% tab title="💈範例" %}
```swift
// NSRegularExpression, NSString.range(of:)
import Foundation

// One or more characters followed by an "@",
// then one or more characters followed by a ".",
// and finishing with one or more characters
let emailPattern = #"^\S+@\S+\.\S+$"#

// Matching Examples
// user@domain.com
// firstname.lastname-work@domain.com

// ----------- method 1: string.range() -------------

// ⭐️ 1. string.range()
let range = "test@test.com".range(
    of: emailPattern,
    options: .regularExpression
)
// range: Range<String.Index>?

// ----------- method 2: regex.matches() -------------

// ⭐️ 2.1 NSRegularExpression
let emailRegex = try! NSRegularExpression(
    pattern: emailPattern, options: []
)

// ⭐️ 2.2 NSRange
let source = "test@test.com"
let sourceRange = NSRange(
    source.startIndex ..< source.endIndex,
    in: source
)

// ⭐️ 2.3 regex.matches()
let matches = emailRegex.matches(
    in: source,
    options: [],
    range: sourceRange
)
// matches: [NSTextCheckingResult]

```
{% endtab %}

{% tab title="📗 參考" %}
* [ ] Advanced Swift ⟩
  * [ ] [Email, Phone, Username, Password, and Date Regular Expressions in Swift](https://www.advancedswift.com/regular-expressions/)
  * [ ] [Regular Expression Capture Groups in Swift](https://www.advancedswift.com/regex-capture-groups/)
* [ ] Paul ⟩ [How to use regular expressions in Swift](https://www.hackingwithswift.com/articles/108/how-to-use-regular-expressions-in-swift)
* [ ] Loaf ⟩ [Getting Started with Swift Regex](https://useyourloaf.com/blog/getting-started-with-swift-regex/) ([swift-5.7](../features/swift/swift-5.7 "mention"))
{% endtab %}

{% tab title="📘 手冊" %}
* Foundation ⟩ [NSString](https://developer.apple.com/documentation/foundation/nsstring)
  * [.range(of:)](https://developer.apple.com/documentation/foundation/nsstring/1410144-range)
  * [range(of:options:)](https://developer.apple.com/documentation/foundation/nsstring/1416849-range)
  * [NSString.CompareOptions](https://developer.apple.com/documentation/foundation/nsstring/compareoptions)
{% endtab %}

{% tab title="🛠 工具" %}
* [Swift Regex](https://swiftregex.com/)
{% endtab %}
{% endtabs %}
