import Foundation
let pattern = ##"(?P<assign_op>(\:|\!|\?)?=)|(?P<token_subst>$|%(\<\@))|(?P<token_ident>[\w\d\.\,]+)|(?P<target_name_match>%\.?)|(?P<token_rule_sep>[:])|(?P<incr_op>\n)|(?P<line_end>\n)|(?P<comment_op>#[.*]+$)|(?P<adjust_parser>[\$%\s\t\:])"##
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = ##"""
CC := nasm
BOOT_REQ := text.o
FREELDR_SRCS := freeldr.c
IMG_NAME := boot.img
TEXT_SECTION := 7c00
# UFS2, ZFS and/or RAW
FILESYSTEMS :=
CPU_FLAGS := PAE
SDK_FLAGS :=
VERSION := "1.00.00"
%.o:
$(ASM) ${SDK_FLAGS} -f bin -o $@ $(patsubst %.bin,%.asm,$@))
${IMG_NAME}:
$(BOOT_REQ) $(FREELDR_SRCS:.c=.o)
"""##
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