[Solved] Regular Expression generation in Swift [duplicate]


You could do something like this :

let str = "_h Hello _h _h World _h"

let range =  NSRange(str.startIndex..., in: str)

let regex = try! NSRegularExpression(pattern: "(?<=_h).+?(?=_h)")

let matches = regex.matches(in: str, range: range)

let results: [String] = matches.compactMap { match in
    let subStr = String(str[Range(match.range, in: str)!]).trimmingCharacters(in: .whitespacesAndNewlines)
    return subStr.isEmpty ? nil : subStr
}

print(results)  //["Hello", "World"]

Here is the regex explained :

  • (?<=_h) : Positive lookbehind for _h literally (case sensitive);
  • .+? : Matches any character (except for line terminators), between 1 and unlimited times, as few times as possible, expanding as needed;
  • (?=_h) : Positive lookahead for _h literally (case sensitive).

N.B : Force-unwrapping when constructing subStr is safe.

solved Regular Expression generation in Swift [duplicate]