import Foundation
let pattern = ##"""
(?(DEFINE)
(?<nestedBrackets> \[ [^][]* (?:\g<nestedBrackets>[^][]*)*+ ] )
)
(?: # two possible entry points
\G(?!\A) # 1. contiguous to a previous match
| # OR
[^[]* \[ # 2. all characters until an opening bracket
)
# all possible characters until "," or the closing bracket:
[^]["]* # all that is not ] [ or "
(?:
\g<nestedBrackets> [^]["]* # possible nested brackets
| # OR
"(?!,") [^]["]* # a quote not followed by ,"
)*+ # repeat as needed
\K # remove all on the left from match result
(?:
"," # match the target
|
] (*SKIP)(*F) # closing bracket: break the contiguity
)
"""##
let regex = try! NSRegularExpression(pattern: pattern, options: .allowCommentsAndWhitespace)
let testString = #"[word:"pla pla","pla pla","[other_word:"pla pla","[word:"pla","pla"end word]","pla pla"end other_word]","pla pla","[word:"pla","pla"end word]"end word]",""#
let stringRange = NSRange(location: 0, length: testString.utf16.count)
let substitutionString = #"|,|"#
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