import Foundation
let pattern = ##"(?:\bclass \w+\s*{\s*|\G(?!\A)\s*(?:(?://|#).*$|/\*[\s\S]*?\*/|\bconst[^;]*;)\s*)\K(\$\w+\s*(?:;|=.*;))"##
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = ##"""
class MyClass {
$myvar1;
// some comment here (even with a variable $x;)
$myvar2;
/* I have a multiline comment here
with a variable $x; here
*/
$myvar3;
# Just another comment $x;
$myvar4;
const SOMETHING;
$myvar5;
function __construct($myvar1 = NULL, $myvar2 = array()) {
$this->myvar1 = $myvar1;
$this->myvar2 = $myvar2;
}
}
"""##
let stringRange = NSRange(location: 0, length: testString.utf16.count)
let substitutionString = #"private $1"#
let result = regex.stringByReplacingMatches(in: testString, range: stringRange, withTemplate: substitutionString)
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