import Foundation
let pattern = #"^ *[^\s]+( +[^\s]+)*$"#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = ##"""
# UFIS : User-Friendly and Instant Installer System
# Each comment starts with '#' and ends with a new line.
# Each statement is written in one line.
# Commands' and built-in variables' names are always uppercase.
# A custom variable name must have at least one lowercase character and must begin with a letter or the underscore (_).
LET APP_NAME = "MyApp"
LET APP_VERSION = "1.0.0"
LET a = MATERIAL "folderx/"
a -= "test.exe"
a -= "main.exe"
a += MATERIAL "folderz/"
a += MATERIAL "README.md"
LET b = MATERIAL "folderx/test.exe"
LET c = MATERIAL "folderx/main.exe"
IF INSTALLING
LET iAcceptLicense = INPUT CHECKBOX "Accept [license](https://myapp.com/license)" MANDATORY
IF iAcceptLicense == FALSE
QUIT
ENDIF
LET iLanguage = INPUT CHOICES "Vietnamese" OR "English" DEFAULT "English" MANDATORY
LET INSTALL_DIR = INPUT DIRECTORY "Installation directory" POSTFIX "/${APP_NAME}" DEFAULT PROGRAM_FILES
LET iInstallTest = INPUT CHECKBOX "Install test.exe" DEFAULT FALSE
LET iCreateDesktopShortcut = INPUT CHECKBOX "Create desktop shortcut" DEFAULT TRUE
LET iLaunchAtStartup = INPUT CHECKBOX "Launch program at startup" DEFAULT TRUE
INSTALL a AND c TO INSTALL_DIR # the same as "${INSTALL_DIR}"
IF iInstallTest == TRUE
INSTALL b TO INSTALL_DIR AS "test_program.exe"
ENDIF
IF iCreateDesktopShortcut == TRUE
CREATE SHORTCUT FOR c IN DESKTOP_ALL_USERS
ENDIF
IF iLaunchAtStartup == TRUE
RUN c AT STARTUP
ENDIF
WORK registry_work
CREATE REGSZ "HKEY_LOCAL_MACHINE/Software/${APP_NAME}" VALUE "1"
ENDWORK
CPP
#include <iostream>
void entry() {
std::cout << "Not very intelligent";
}
ENDCPP
CALL entry
ELIF RUNNING
RUN c
ELSE # UNINSTALLING
UNDO ALL EXCEPT registry_work
ENDIF
"""##
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