To find IPv4 addresses in a string using regular expressions in Swift, we need to define a pattern that matches IPv4 addresses. The pattern should consist of four sets of digits separated by dots, where each set consists of 1-3 digits. Here's the regular expression pattern in Swift:
main.swift40 chars2 lines
Next, we use NSRegularExpression
class to create a regular expression object from the pattern. Then we can use this object to search for matches in the input string.
main.swift256 chars4 lines
The matches
array contains all the ranges in the input string that match the regex pattern. To extract the matched IPv4 addresses, we can use the substring(with:)
method of the input string.
main.swift141 chars6 lines
This will print:
main.swift21 chars3 lines
Here's the complete code:
main.swift553 chars16 lines
gistlibby LogSnag