import Foundation
// WARNING: You included a flag that Swift doesn't support: X
// When this flag is set, it causes any backslash in the pattern that is followed by a letter that has no special meaning to cause an error.
// By default in Swift, a backslash followed by a letter with no special meaning will be treated as a literal.
// WARNING: You included a flag that Swift doesn't support: u
// When this flag is set, it makes the pattern and subject strings to be treated as unicode.
// Swift already treats the pattern and subject strings as unicode by default, so including this flag is redundant.
let pattern = ##"""
(?(DEFINE)
(?<tagName>
[a-z][a-z\d]*+ (?=[>\s/])
)
(?<tagAttr>
(?>
[^>"']++
| " [^"]*+ "
| ' [^']*+ '
)*+
)
)
< (li|/ul) /?+ (?=[>\s/]) ((?&tagAttr)) >
((?:
[^<]++
| < /?+ (?!(?:li|ul)(?=[>\s/])) (?&tagName) (?&tagAttr) > #any tag except <li> and <ul>
| < (?! /?+ (?&tagName) ) #not tag
)*)
(?= < (?:li|/ul) (?=[>\s/]) (?&tagAttr) ) #check for nested <li> and <ul>
"""##
let regex = try! NSRegularExpression(pattern: pattern, options: [.caseInsensitive, .allowCommentsAndWhitespace, .dotMatchesLineSeparators])
let testString = #"""
<ul>
<li fhgfhfg ghgfhfghhfgh= ghghg="..." a = 'ghghg'>dfdsfsd
<ul>
<li>111</li>
<li/>2222
<li>mmmmm</li>
</ul>
<li>dfdsfdsfsdf <b class="..."><br/>fgdfgd<i></b><!-- dfdf--><li>
<li>
<li>dsfsdfsdfdsf
</ul>
"""#
let stringRange = NSRange(location: 0, length: testString.utf16.count)
let substitutionString = #"<$3$4>$5</LI>\r"#
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