import Foundation
let pattern = #"matei 200 inheritance"#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = #"""
<?php
class Device {
protected $name;
protected $isOn = false;
function __construct($name = "Unknown Device") {
$this->name = $name;
}
function turnOn() {
$this->isOn = true;
echo "{$this->name} is turned on.<br>";
}
function turnOff() {
$this->isOn = false;
echo "{$this->name} is turned off.<br>";
}
function getStatus() {
$status = $this->isOn ? "on" : "off";
echo "{$this->name} is currently {$status}.<br>";
}
}
class Smartphone extends Device {
private $photos = 0;
function __construct($name = "Smartphone") {
parent::__construct($name);
}
function takePhoto() {
if ($this->isOn) {
$this->photos++;
echo "Photo taken! (Total: {$this->photos} photos)<br>";
} else {
echo "Please turn on the {$this->name} first!<br>";
}
}
function showPhotoCount() {
echo "Number of photos: {$this->photos}<br>";
}
}
echo "<h3>Device Class:</h3>";
$myDevice = new Device("Television");
$myDevice->turnOn();
$myDevice->getStatus();
$myDevice->turnOff();
$myDevice->getStatus();
echo "<br><h3>Smartphone Class:</h3>";
$myPhone = new Smartphone("iPhone 15");
$myPhone->getStatus();
$myPhone->takePhoto();
$myPhone->turnOn();
$myPhone->takePhoto();
$myPhone->takePhoto();
$myPhone->takePhoto();
$myPhone->showPhotoCount();
$myPhone->turnOff();
?>
"""#
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