import Foundation
let pattern = #"(\d.+)(?=\s*\" Unit=\"W\" Type=\"AC_Power\")"#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = #"""
<Measurements>
<Measurement Value="237.6" Unit="V" Type="AC_Voltage"/>
<Measurement Value="9.828" Unit="A" Type="AC_Current"/>
<Measurement Value="2344.7" Unit="W" Type="AC_Power"/>
<Measurement Value="2343.4" Unit="W" Type="AC_Power_fast"/>
<Measurement Value="50.003" Unit="Hz" Type="AC_Frequency"/>
<Measurement Value="294.4" Unit="V" Type="DC_Voltage1"/>
<Measurement Value="171.3" Unit="V" Type="DC_Voltage2"/>
<Measurement Value="8.056" Unit="A" Type="DC_Current1"/>
<Measurement Unit="A" Type="DC_Current2"/>
<Measurement Value="343.8" Unit="V" Type="LINK_Voltage"/>
<Measurement Unit="W" Type="GridPower"/>
<Measurement Unit="W" Type="GridConsumedPower"/>
<Measurement Unit="W" Type="GridInjectedPower"/>
<Measurement Unit="W" Type="OwnConsumedPower"/>
<Measurement Value="100.0" Unit="%" Type="Derating"/>
</Measurements>
</Device>
</root>
"""#
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