Is there a way in UIPasteboard to create a custom DetectionPattern with regular expressions?

264 Views Asked by At

I'm trying to use the UIPasteboard.general.detectPatterns function to identify specific custom patterns. The documentation suggests that I can create my own DetectionPattern, but I'm having trouble finding out how to do that.

For example, to detect flight numbers, I can use the following code snippet:

            UIPasteboard.general.detectPatterns(for: [\.flightNumbers], completionHandler: { result in

                switch result {
                case .success(let detectedPatterns):
                    if detectedPatterns.contains(\.flightNumbers) {
                        print(UIPasteboard.general.string)
                    } else {
                        // We won't be retrieving the value, so we won't get a notification banner
                        break
                    }


                case .failure(_): break

                }
            })

I'd like to achieve a similar result using custom patterns defined with regular expressions.

I have tried to use:

UIPasteboard.DetectionPattern(rawValue: )

However, I did not succeed.

1

There are 1 best solutions below

1
trinity natalia On

Here is the code:

UIPasteboard's detectPatterns API doesn't natively support custom patterns based on regular expressions. The available detection patterns are predefined, and creating new patterns directly through UIPasteboard.DetectionPattern isn't supported.

However, if you need to identify custom patterns using regular expressions, you'd need to retrieve the content of the pasteboard and apply your regex detection logic on it. For instance:

let pasteboardContent = UIPasteboard.general.string
let regexPattern = "YOUR REGEX PATTERN HERE"
let regex = try? NSRegularExpression(pattern: regexPattern)

if let matches = regex?.matches(in: pasteboardContent ?? "", options: [], range: NSRange(location: 0, length: pasteboardContent?.count ?? 0)), !matches.isEmpty {
    print("Pattern found!")
} else {
    print("Pattern not found.")
}

This code manually checks for the regex pattern within the UIPasteboard's string content.