import Foundation
let pattern = ##"^\s*(#*)\s*(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s+([a-zA-Z0-9\.\- ]+)([^#]*#?\w*\s*)$"##
let regex = try! NSRegularExpression(pattern: pattern, options: [.anchorsMatchLines, .caseInsensitive])
let testString = #############################################################"""
# Copyright (c) 1993-2009 Microsoft Corp.
#
# This is a sample HOSTS file used by Microsoft TCP/IP for Windows.
#
# This file contains the mappings of IP addresses to host names. Each
# entry should be kept on an individual line. The IP address should
# be placed in the first column followed by the corresponding host name.
# The IP address and the host name should be separated by at least one
# space.
#
# Additionally, comments (such as these) may be inserted on individual
# lines or following the machine name denoted by a '#' symbol.
#
# For example:
#
# 102.54.94.97 rhino.acme.com # source server
# 38.25.63.10 x.acme.com # x client host
# localhost name resolution is handled within DNS itself.
# 127.0.0.1 localhost
# ::1 localhost
127.0.0.1 jw smartsite.jw
127.0.0.1 dev.filepresso.com dev.filepresso.com.pl dev.filepresso.pl dev.filefly.pl
#### 89.31.66.248 sp.biatelbit.pl
192.168.72.51 subversion.biatel.com.pl
# 127.0.0.1 bip.smartsite.bit-sa.pl
# 127.0.0.1 bip.augustow.wrotapodlasia.pl
127.0.0.1 rpowp.smartsite.bit-sa.pl
127.0.0.1 cms.smartsite.bit-sa.pl
127.0.0.1 cms-test.smartsite.bit-sa.pl
############################################################
#
# UMWP
#
############################################################
############################################################
# ST - test - UMWP
############################################################
#10.200.14.70 ST-sapp1
#10.200.14.70 tv.smartsite.bit-sa.pl wp.smartsite.bit-sa.pl cms.smartsite.bit-sa.pl test.smartsite.bit-sa.pl bip.smartsite.bit-sa.pl si.smartsite.bit-sa.pl sspw.wrotapodlasia.pl
#10.200.14.70 radny.smartsite.bit-sa.pl stats.smartsite.bit-sa.pl test9.smartsite.bit-sa.pl
"""#############################################################
let stringRange = NSRange(location: 0, length: testString.utf16.count)
let matches = regex.matches(in: testString, range: stringRange)
var result: [[String]] = []
for match in matches {
var groups: [String] = []
for rangeIndex in 1 ..< match.numberOfRanges {
let nsRange = match.range(at: rangeIndex)
guard !NSEqualRanges(nsRange, NSMakeRange(NSNotFound, 0)) else { continue }
let string = (testString as NSString).substring(with: nsRange)
groups.append(string)
}
if !groups.isEmpty {
result.append(groups)
}
}
print(result)
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Swift 5.2, please visit: https://developer.apple.com/documentation/foundation/nsregularexpression