To find Ethereum addresses in a string using regex in Swift, you can use the following code:
main.swift578 chars12 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 itThe 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