import Foundation
let pattern = #"(--[\w-]+:[\s]*[^;\n}]+)"#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = ##"""
these should match
:root {
--externalcolor: red;
--samename: orange;
--samename: #0f0;
--foo: green;
--FOO: #0f0;
--halfsuccess: orange;
/* multiple on one line */
--success: green;--success2: #0f0;
/* forget the ; */
--success: green
--success2: #0f0
--fred: var(--foo);
--barney: var(--foo, test)
}
:root {
/* name options */
--4name: startsWithNumber;
--name: startsWithLetter;
/* value options */
--startWithLetter: red;
--startWithPound: #0f0;
--startWithNumber: 20px;
--startWithQuoteDouble: "test";
--startWithQuoteSingle: 'test';
--containsUrl: url("http://test.com/foo?a=b&c=d");
--containsPunctuation: -_,.;
--containsSpace: "test space";
/* misc conditions*/
--multipleOnOneLine1: green; --multipleOnOneLine2: #0f0;
--noSpaceAfterColon:test;
--multiSpaceAfterColon: test;
--dash-in-name: test;
--underscore_in_name: test;
}
/* minified css */
:root{--almost-black:#222;}html{color:var(--almost-black)}body{color:var(--almost-black);
don't match this (the double dash in the comments
/* ----------------------------------------------------- */
@import url("https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap");
on one line
/* ----------------------------------------------------- */ @import url("https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap");
"""##
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