find ethereum addresses in a string using regex in swift

To find Ethereum addresses in a string using regex in Swift, you can use the following code:

main.swift
func findEthereumAddresses(in text: String) -> [String] {
    let pattern = "(?:^|\\s)(?:0x)[0-9a-fA-F]{40}(?:\\s|$)"
    let regex = try? NSRegularExpression(pattern: pattern, options: [])
    let range = NSRange(text.startIndex..<text.endIndex, in: text)
    let matches = regex?.matches(in: text, options: [], range: range) ?? []
    return matches.map { match in
        let start = text.index(text.startIndex, offsetBy: match.range.lowerBound)
        let end = text.index(text.startIndex, offsetBy: match.range.upperBound)
        return String(text[start..<end])
    }
}
578 chars
12 lines

This function takes a string text and returns an array of strings that represent Ethereum addresses. It uses a regular expression pattern "(?:^|\\s)(?:0x)[0-9a-fA-F]{40}(?:\\s|$)" that matches Ethereum addresses in the string. Here's what the pattern means:

  • (?:^|\\s) matches the beginning of the string or any whitespace character, but does not capture it
  • (?:0x) matches the prefix "0x", but does not capture it
  • [0-9a-fA-F]{40} matches any 40 hexadecimal digits, which is the length of an Ethereum address
  • (?:\\s|$) matches the end of the string or any whitespace character, but does not capture it

The function uses NSRegularExpression to create a regex object, and then uses matches(in:options:range:) to find all matches of the pattern in the string. It then returns an array of the matched substrings by using map to extract them from the NSTextCheckingResult objects returned by matches. Note that the function assumes that there is at most one Ethereum address per whitespace-separated word; if that's not the case, the pattern will need to be modified.

gistlibby LogSnag